请帮我写一段unicode码转换成utf8的C语言代码
时间: 2023-05-19 11:02:31 浏览: 115
以下是一段unicode码转换成utf8的C语言代码:
```c
#include <stdio.h>
void unicode_to_utf8(unsigned int unicode, char *utf8) {
if (unicode <= 0x7f) {
utf8[0] = (char)unicode;
utf8[1] = '\0';
} else if (unicode <= 0x7ff) {
utf8[0] = (char)(0xc0 | (unicode >> 6));
utf8[1] = (char)(0x80 | (unicode & 0x3f));
utf8[2] = '\0';
} else if (unicode <= 0xffff) {
utf8[0] = (char)(0xe0 | (unicode >> 12));
utf8[1] = (char)(0x80 | ((unicode >> 6) & 0x3f));
utf8[2] = (char)(0x80 | (unicode & 0x3f));
utf8[3] = '\0';
} else if (unicode <= 0x10ffff) {
utf8[0] = (char)(0xf0 | (unicode >> 18));
utf8[1] = (char)(0x80 | ((unicode >> 12) & 0x3f));
utf8[2] = (char)(0x80 | ((unicode >> 6) & 0x3f));
utf8[3] = (char)(0x80 | (unicode & 0x3f));
utf8[4] = '\0';
}
}
int main() {
unsigned int unicode = 0x4e2d; // 中的unicode码
char utf8[5];
unicode_to_utf8(unicode, utf8);
printf("%s\n", utf8); // 输出:中
return 0;
}
```
希望能对你有所帮助!
阅读全文