c++之gbk和utf8编码转换

1.gbk转换成utf8

void GBKTOUTF8(string& strGBK)//转码 GBK编码转成UTF8编码
{
	int len = MultiByteToWideChar(CP_ACP,0, strGBK.c_str(), - 1, NULL, 0); 
	wchar_t* wszUtf8 = new wchar_t[len]; 
	memset(wszUtf8, 0, len);
	MultiByteToWideChar(CP_ACP, 0, strGBK.c_str(), - 1, wszUtf8, len); 
	len = WideCharToMultiByte(CP_UTF8, 0, wszUtf8, -1, NULL,0,NULL,NULL);
	char* szUtf8 = new char[len + 1];
	memset(szUtf8, 0, len + 1);
	WideCharToMultiByte(CP_UTF8, 0, wszUtf8, -1, szUtf8, len, NULL, NULL);
	strGBK = szUtf8;
	delete[] szUtf8;
	delete[] wszUtf8;
}

2.utf8转换成gbk

std::string UTF8ToGBK(const char* strUTF8)//UTF8编码转成GBK编码
{
	int len = MultiByteToWideChar(CP_UTF8, 0, strUTF8, -1, NULL, 0);
	wchar_t* wszGBK = new wchar_t[len + 1];
	memset(wszGBK,0, len * 2 + 2);
	MultiByteToWideChar(CP_UTF8,0, strUTF8, - 1, wszGBK, len); 
	len = WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, NULL, 0, NULL, NULL);
	char* szGBK = new char[len + 1];
	memset(szGBK,0, len + 1);
	WideCharToMultiByte(CP_ACP, 0, wszGBK, - 1, szGBK,len, NULL, NULL); 
	std::string strTemp(szGBK);
	if (wszGBK) delete[] wszGBK;
	if (szGBK) delete[] szGBK;
	return strTemp;
}

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
C++中,u8字符串字面量(即以u8开头的字符串)可以用于表示UTF-8编码的字符串。如果你已经有一个使用国标编码(GB2312或GBK)表示的字符串,可以使用一些库来将其转换为UTF-8编码。 例如,使用iconv库可以很方便地进行编码转换。以下是一个使用iconv库将国标编码字符串转换为UTF-8编码字符串的示例: ```cpp #include <iostream> #include <string> #include <iconv.h> int main() { std::string gb_str = "你好,世界!"; // 使用国标编码表示的字符串 std::string utf8_str; // 转换后的UTF-8编码字符串 iconv_t conv = iconv_open("UTF-8", "GB18030"); // 创建一个转换句柄 if (conv == (iconv_t)(-1)) { std::cerr << "Failed to create conversion handle." << std::endl; return 1; } char* gb_ptr = const_cast<char*>(gb_str.c_str()); std::size_t gb_len = gb_str.length(); char utf8_buf[1024]; char* utf8_ptr = utf8_buf; std::size_t utf8_len = sizeof(utf8_buf); int result = iconv(conv, &gb_ptr, &gb_len, &utf8_ptr, &utf8_len); // 进行编码转换 if (result == -1) { std::cerr << "Failed to convert encoding." << std::endl; return 1; } utf8_str.assign(utf8_buf, sizeof(utf8_buf) - utf8_len); // 从转换后的缓冲区中取出转换后的字符串 iconv_close(conv); // 关闭转换句柄 std::cout << "gb_str: " << gb_str << std::endl; std::cout << "utf8_str: " << utf8_str << std::endl; return 0; } ``` 需要注意的是,在进行编码转换时要确保源字符串的编码和目标编码是正确的,否则可能会得到错误的结果。在上面的示例中,我们将源编码设置为GB18030,这是GB2312和GBK的超集,通常也可以用于表示这两种编码

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱笑的蛐蛐

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值