1. 程式人生 > >[智慧家居]Linux 字元編碼的轉換

[智慧家居]Linux 字元編碼的轉換

1.專案需求:GB2312轉UTF編碼

2.思路:iconv庫的使用

3.程式碼例項

/************************************************
*   @FileName     : gb2utf.c
*   @Description  : Code convert
*   @Editor       : Donkey
*   @Date         : 2018-12-01  13:07
*************************************************/
#include "UtfGb.h"

int code_convert(char *from_charset,char *to_charset,char *inbuf,ssize_t inlen,char *outbuf,ssize_t outlen)
{
    iconv_t cd;
    char **pin = &inbuf;
    char **pout = &outbuf;
    
    cd = iconv_open(to_charset,from_charset);
    if (cd==0) return -1;
    memset(outbuf,0,outlen);
    if (iconv(cd,pin,&inlen,pout,&outlen)==-1) return -1;
    iconv_close(cd);
    return 0;
}

int g2u(char * inbuf, int inlen, char* outbuf, int outlen){
    return code_convert("gb2312", "utf-8", inbuf, inlen, outbuf, outlen);
}

int main(int argc, const char * argv[]) {
  char in[] = {0xD4,0xB6,0xB3,0xCC,0xBF,0xAA,0xCB,0xF8};
  char buf[20]={0};
  int len = 20;
  int l=8;
  g2u(in, l, buf, len);

  printf("%s\n",buf);

  return 0;
}

4.輸出