linux下UTF-8和GB2312之间转换
2012-11-21 10:26
661 查看
最近在做中文的处理,需要在UTF8和GB2312之间进行转换,就简单封装了一下。
记下来,备忘!
注:需要头文件 iconv.h 和 errno.h
记下来,备忘!
注:需要头文件 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"; } }
相关文章推荐
- linux下UTF-8和GB2312之间转换
- linux下UTF-8和GB2312之间转换
- throws ; 编码 gb2312和utf-8之间转换
- Linux下Gb2312与UTF-8的转换
- 字符集之间转换(UTF-8,UNICODE,Gb2312)
- 字符集之间转换(UTF-8,UNICODE,Gb2312)
- UTF-8、Unicode、Gb2312编码之间的转换类
- 字符集之间转换(UTF-8,UNICODE,Gb2312)
- linux C C++ 字符集转换,UTF-8,GB2312
- c++字符集之间转换(UTF-8,UNICODE,Gb2312)
- 字符编码知识:Unicode、UTF-8、ASCII、GB2312等编码之间是如何转换的?[转]
- 字符集之间转换(UTF-8,UNICODE,Gb2312)
- Linux下Gb2312与UTF-8的转换
- 字符编码知识:Unicode、UTF-8、ASCII、GB2312等编码之间是如何转换的?
- (转)字符集之间转换(UTF-8,UNICODE,Gb2312)
- 字符集之间转换(UTF-8,UNICODE,Gb2312) c++
- linux C C++ 字符集转换,UTF-8,GB2312
- 字符编码知识:Unicode、UTF-8、ASCII、GB2312等编码之间是如何转换的
- 视频安防监控平台-GB2312和UTF-8在linux下面的转换
- GB2312、UTF_8、UNICODE之间相互转换