Skip to content

Instantly share code, notes, and snippets.

@mk270
Created April 12, 2012 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mk270/2367693 to your computer and use it in GitHub Desktop.
Save mk270/2367693 to your computer and use it in GitHub Desktop.
Convert ISO-8859-1 to UTF-8 with constant RAM (cf iconv)
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#define MAX 4096
void die(const char *s) {
perror(s);
exit(1);
}
int convert(int fd_in, int fd_out) {
char buffer[MAX];
char output[MAX*2];
int bytes;
char *i, *o;
while(0 < (bytes = read(STDIN_FILENO, buffer, MAX))) {
if(bytes == -1) { die("read"); }
for(i = buffer, o = output; i < buffer + bytes; i++, o++) {
if(*i & 0x80) {
*o = 0xc0 | ((*i & 0xc0) >> 6);
o++;
*o = 0x80 | (*i & 0x3f);
} else {
*o = *i;
}
}
bytes = write(STDOUT_FILENO, output, o - output);
if (bytes == -1) { die("write"); }
}
return 0;
}
int main(int argc, char *argv[], char *env[]) {
exit(convert(STDIN_FILENO, STDOUT_FILENO));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment