字符集GB2312判断及UTF8相互转换

由各网络信息整理




/* 代码转换:从一种编码转为另一种编码 */
static int32_t code_convert(char_t *from_charset, char_t *to_charset, char_t *inbuf, int32_t inlen, char_t *outbuf, int32_t outlen)
{
    iconv_t cd;
    int32_t rc;
    char_t **pin = &inbuf;
    char_t **pout = &outbuf;
    size_t in = (size_t)inlen;
    size_t out = (size_t)outlen;

    cd = iconv_open(to_charset,from_charset);
    if (cd == 0)
        return -1;
    memset(outbuf,0,outlen);
    if (iconv(cd, pin, &in, pout, &out) == -1)
        return -1;
    iconv_close(cd);
    return 0;
}

/* UNICODE码转为GB2312码 */
int32_t u2g(char_t *inbuf, int32_t inlen, char_t *outbuf, int32_t outlen)
{
    return code_convert("UTF-8", "GB2312", inbuf, inlen, outbuf, outlen);
}

/* GB2312码转为UNICODE码 */
int32_t g2u(char_t *inbuf, int32_t inlen, char_t *outbuf, int32_t outlen)
{
    return code_convert("GB2312", "UTF-8", inbuf, inlen, outbuf, outlen);
}

/* 1、判断是否是GB2312 ==0 true  ==-1  false */
int32_t is_gb_code(const char_t *str)
{
    uchar_t ch1;
    uchar_t ch2;
 
    if (strlen(str) >= 2)
    {
        ch1 = (uchar_t)str[0];
        ch2 = (uchar_t)str[1];

        if (ch1>=176 && ch1<=247 && ch2>=160 && ch2<=254)
            return 0;
        else return 1;
    }
    else return 1;
}

/* 2、判断是否是GBK编码 ==0 true  ==-1  false */
int32_t is_gbk_code(const char_t *str)
{
    uchar_t ch1;
    uchar_t ch2;

    if (strlen(str) >= 2)
    {
        ch1 = (uchar_t)str[0];
        ch2 = (uchar_t)str[1];
        if (ch1>=129 && ch1<=254 && ch2>=64 && ch2<=254)
            return 0;
        else return 1;
    }
    else return 1;
}

/*
3、判断是否为Big5
它的范围为:高字节从0xA0到0xFE,低字节从0x40到0x7E,和0xA1到0xFE两部分。判断一个汉字是否是BIG5编码,可以如上对字符的编码范围判断即可。
*/



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值