another example
[tridge/junkcode.git] / ucs_to_utf8.c
1 #include <stdio.h>
2 #include <iconv.h>
3
4 static int utf8_encode(unsigned char c[4], unsigned uc)
5 {
6         unsigned char uc1, uc2;
7         uc1 = uc & 0xFF;
8         uc2 = uc >> 8;
9
10         if ((uc2 & 0xf8) == 0xd8) {
11                 c[0] = 0xed;
12                 c[1] = 0x9f;
13                 c[2] = 0xbf;
14                 c[3] = 0;
15                 return 3;
16         }
17
18         if (uc2 & 0xf8) {
19                 c[0] = 0xe0 | (uc2>>4);
20                 c[1] = 0x80 | ((uc2&0xF)<<2) | (uc1>>6);
21                 c[2] = 0x80 | (uc1&0x3f);
22                 c[3] = 0;
23                 return 3;
24         }
25
26         if (uc2 | (uc1 & 0x80)) {
27                 c[0] = 0xc0 | (uc2<<2) | (uc1>>6);
28                 c[1] = 0x80 | (uc1&0x3f);
29                 c[2] = 0;
30                 return 2;
31         } 
32
33         c[0] = uc1;
34         c[1] = 0;
35
36         return 1;
37 }
38
39 int main(int argc, char *argv[])
40 {
41         int i;
42         
43
44         for (i=1;i<argc;i++) {
45                 char s[4];
46                 unsigned c;
47
48                 c = strtol(argv[i], NULL, 16);
49
50                 int len = utf8_encode(s, c);
51
52                 s[len] = '\n';
53                 write(1, s, len+1);
54         }
55
56         return 0;
57 }