您的位置:首页 > 运维架构 > Linux

linux下UTF-8和GB2312之间转换

2012-11-21 10:26 661 查看
最近在做中文的处理,需要在UTF8和GB2312之间进行转换,就简单封装了一下。

记下来,备忘!

注:需要头文件 iconv.h 和 errno.h

/**
* @name 字符编码枚举
* 可以在这里增加更多的编码支持,具体可以man iconv看下
*/
typedef enum
{
CP_UTF8 = 0,                    /// UTF-8 编码
CP_GB2312                       /// GB2312 编码
} CP;

int convertCP(const char* pszSrc, size_t nSrcLen,
char* pszDst, size_t& nDstLen, CP from, CP to)
{
if (NULL == pszSrc || NULL == pszDst || 0 == nSrcLen || 0 == nDstLen)
{
return -3;
}

if (from == to)
{
if (nDstLen < nSrcLen)
return -2;
else
strncpy(pszDst, pszSrc, nSrcLen);
return 0;
}

// 进行转码
iconv_t cd = iconv_open(get_CP_str(to), get_CP_str(from));

if (0 == cd)
{
return -1;
}

memset(pszDst, 0, nDstLen);

  size_t nOldLen = nSrcLen;
if (static_cast<size_t>(-1) == iconv(cd,
const_cast<char**>(&pszSrc), &nSrcLen, &pszDst, &nDstLen))
{
iconv_close(cd);
if (E2BIG == errno)
return -2;
return -3;
}
  nDstLen = nOldLen - nDstLen; // 转换的字节数
iconv_close(cd);

return 0;
}

const char* get_CP_str(CP code)
{
// IGNORE 可以使得 iconv 函数忽略非法字符
switch (code)
{
case CP_GB2312:
return "gb2312//IGNORE";

case CP_UTF8:
default:
return "utf-8//IGNORE";
}
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: