linux ascii转换 utf8,C++中ASCII、unicode与Utf8之间的相互转化

一、windows下转换方法:

// 当type为CP_ACP时,GBK转化为UNICODE;当type为CP_UTF8时,UTF8转化为UNICODE

wchar_t* trans(const char * ch, int type = CP_ACP) {

int len = MultiByteToWideChar(type, 0, ch, -1, nullptr, 0);

wchar_t *str = new wchar_t[len + 1];

wmemset(str, 0, len + 1);

MultiByteToWideChar(type, 0, ch, -1, str, len);

return str;

}

// 当type为CP_ACP时,UNICODE转化为GBK;当type为CP_UTF8时,UNICODE转化为UTF8

char* trans(const wchar_t * wch, int type = CP_ACP) {

int len = WideCharToMultiByte(type, 0, wch, -1, nullptr, 0, nullptr, nullptr);

char *str = new char[len + 1];

memset(str, 0, len + 1);

WideCharToMultiByte(type, 0, wch, -1, str, len, nullptr, nullptr);

return str;

}

注意:

转换后的字符串,使用之后,需要delete掉。

二、linux下转换方法:

bool trans(const char *pFromCode,const char *pToCode,const char *pInBuf,size_t iInLen,char *pOutBuf,size_t iOutLen)

{

//打开字符集转换

iconv_t hIconv = iconv_open(pToCode, pFromCode);

if (! hIconv) return false;

//开始转换

size_t iRet = iRet = iconv(hIconv, (char **) (&pInBuf), &iInLen, &pOutBuf, &iOutLen);

//关闭字符集转换

iconv_close(hIconv);

return (bool)iRet;

}

使用方法:

string result = "这是gbk字符串";

char ch[255];

memset(ch,'\0',sizeof(ch));

trans("GBK","UTF-8",result.c_str(),result.size(),ch,sizeof(ch));

注意:

需要安装libiconv的开发包,并引入头文件#include "iconv.h"

三、c++11自带的编码转换器,代码如下:

#include "stdafx.h"

#include #include #include using namespace std;

using WCHAR_GBK= codecvt_byname;

using WCHAR_UTF8= codecvt_utf8;

// linux下为"zh_CN.GBK"

#define GBK_NAME ".936"

int main()

{

// 定义一个utf8字符串

string result = u8"中国人";

// gbk与unicode之间的转换器

wstring_convertcvtGBK(new WCHAR_GBK(GBK_NAME));

// utf8与unicode之间的转换器

wstring_convertcvtUTF8;

// 从utf8转换为unicode

wstring ustr = cvtUTF8.from_bytes(result);

// 从unicode转换为gbk

string str = cvtGBK.to_bytes(ustr);

cout << str << endl;

getchar();

return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值