utf-8转gbk C语言 不用iconv库函数
时间: 2023-07-07 20:11:13 浏览: 50
如果不想使用 `iconv` 库函数,可以手动实现 UTF-8 到 GBK 的转换。具体思路如下:
1. 读取 UTF-8 编码中的一个字符,根据字符的编码范围确定其对应的 Unicode 编码。
2. 根据 Unicode 编码查找对应的 GBK 编码,将 GBK 编码写入输出缓存。
3. 重复上述步骤,直到所有字符都被转换为 GBK 编码。
实现代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int utf8_to_gbk(char *inbuf, size_t inlen, char *outbuf, size_t outlen) {
unsigned char *pin = (unsigned char *)inbuf;
unsigned char *pout = (unsigned char *)outbuf;
unsigned char *pend = (unsigned char *)inbuf + inlen;
unsigned char *pstart = pout;
unsigned int uc, gbk;
while (pin < pend) {
if (*pin < 0x80) {
// 单字节字符,直接转换
*pout++ = *pin++;
} else if (*pin < 0xE0) {
// 双字节字符
uc = (*pin++ & 0x1F) << 6;
uc |= (*pin++ & 0x3F);
gbk = 0;
if (uc >= 0x410 && uc <= 0x4FE) {
gbk = uc - 0x350;
} else if (uc >= 0x2010 && uc <= 0x2017) {
gbk = uc - 0x16A0;
} else if (uc >= 0x25A0 && uc <= 0x25A1) {
gbk = uc - 0x1F00;
} else if (uc == 0x2018) {
gbk = 0xA1;
} else if (uc == 0x2019) {
gbk = 0xA2;
} else if (uc == 0x201C) {
gbk = 0xB1;
} else if (uc == 0x201D) {
gbk = 0xB2;
}
if (gbk != 0) {
*pout++ = gbk >> 8;
*pout++ = gbk & 0xFF;
}
} else {
// 三字节字符,暂不支持
return -1;
}
if (pout - pstart >= outlen) {
// 输出缓存不足
return -1;
}
}
*pout = '\0';
return pout - pstart;
}
int main() {
char *utf8_str = "你好,世界!";
char gbk_str[50];
if (utf8_to_gbk(utf8_str, strlen(utf8_str), gbk_str, sizeof(gbk_str)) != -1) {
printf("GBK string: %s\n", gbk_str);
}
return 0;
}
```
需要注意的是,这个实现方法并不能支持所有的 UTF-8 字符,只支持常用的汉字和标点符号。如果需要支持更多的字符,需要对转换函数进行相应的修改。