Qt ansi编码转utf8编码

13 篇文章 0 订阅
#ifdef _CUR_SYS_LINUX_
#include <iconv.h>
#else
#include <windows.h>
#include <stdio.h>
#endif



QByteArray ViewImage::AnsiToUtf8(QByteArray &ansi)
{
#ifdef _CUR_SYS_LINUX_
	QByteArray utf8;
	char *buf = new char[ansi.size() * 2];
	char utf8Buf[] = { "utf-8" };
	char gb2312Buf[] = { "gb2312" };
	//ansi.resize(ansi.size()*2);
	int code = code_convert(gb2312Buf, utf8Buf, ansi.data(), ansi.size(), buf, 2 * ansi.size());
	if (code == -1) {
		delete[]buf;
		utf8 = "";
		return utf8;
	}
	utf8 = buf;
	delete[]buf;
	return utf8;
#else
	int len;
	QByteArray result;
	//ANSI转UNICODE
	len = MultiByteToWideChar(CP_ACP, NULL, ansi.data(), -1, NULL, 0);
	WCHAR * unicode = new WCHAR[len + 1];
	memset(unicode, 0, len * 2 + 2);
	MultiByteToWideChar(CP_ACP, NULL, ansi.data(), -1, unicode, len);
	//UNICODE转utf8
	len = WideCharToMultiByte(CP_UTF8, 0, unicode, -1, NULL, 0, NULL, NULL);
	char *utf8 = new char[len + 1];
	memset(utf8, 0, len + 1);
	WideCharToMultiByte(CP_UTF8, 0, unicode, -1, utf8, len, NULL, NULL);
	//赋值
	result = utf8;
	delete[] unicode;
	delete[] utf8;
	return result;
#endif
}


使用方法:

	QString utf8_str = QString(AnsiToUtf8(QByteArray(ansi_str.c_str())));

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值