c++ 转化字节码 iconv

在编程通信过程中不同操作系统使用不同字节码,如utf-8, gbk等需要相互转化
linux提供一个系统调用函数来转换字节码 iconv,使用注意不要错误使用转换码

以下为代码演示

#include  
#include  
#include 
#include 

using namespace std; 

class IconvConvertString
{
public:
  IconvConvertString() = delete;
  IconvConvertString(const IconvConvertString &) = delete;
  IconvConvertString& operator = (const IconvConvertString &) = delete;
	IconvConvertString(const char *from_charset, const char *to_charset)
	{ 
		cd = iconv_open(to_charset, from_charset); 
	} 

	~IconvConvertString() 
	{ 
		iconv_close(cd); 
	} 

	size_t ConvertCode(char *inbuf, size_t inlen, char *outbuf, size_t outlen)
	{ 
		char **pin = &inbuf; 
		char **pout = &outbuf; 
		memset(outbuf,0,outlen); 
		return iconv(cd, pin, (size_t *)&inlen, pout, (size_t *)&outlen); 
	}

private: 
	iconv_t cd; 

};

int main()
{
    IconvConvertString icc("utf-8", "gbk"); 
    char *str_input = "缁忓吀 鎷煎崄";
    char outString[512] = {0};
    int ret = icc.ConvertCode(str_input, strlen(str_input), outString, 512);
    printf("ret = %d\n", ret);
    printf("sourceString = %s\n", str_input);
    printf("ConvertString = %s\n", outString);
    char *str_2 = "中文 呢";
  
    IconvConvertString icc2("gbk", "utf-8");
    char out2[512] = { 0 };
    int ret2 = icc2.ConvertCode(str_2, strlen(str_2), out2, 512); 
    printf("ret2 = %d\n", ret2);
    printf("str2 = %s\n", str_2);
    printf("constr2 = %s\n", out2);

    char *str_3 = "中文呢";
    IconvConvertString icc3("utf-8", "gbk");
    char out3[512] = { 0 };
    int ret3 = icc3.ConvertCode(str_3, strlen(str_3), out3, 512); 
    printf("ret3 = %d\n", ret3);
    printf("str3 = %s\n", str_3);
    printf("constr3 = %s\n", out3);
}

演示图片
c++ 转化字节码 iconv_第1张图片
如果有问题请添加QQ-986573837

你可能感兴趣的:(c++)