最近在做项目时遇到这个问题,比如将汉字“冲”转换后为“51B2”,程序使用的是unicode字符集,下面是通过查资料后整理的解决方法:
//---------------------------------------------------------------------
//函数:W2C
//功能:将16位wchar_t转换为 8位char[2]
//参数:w_cn为待转换的16位字符,c_cn[]为转换后的8位字符
//备注:wchar_t的高位字节应该存储在char数组的低位字节
//作者:chuchong
//---------------------------------------------------------------------
void StyleConvert::W2C(wchar_t w_cn , char c_cn[])
{
//following code convert wchar to char
c_cn[0] = w_cn >> 8 ;
c_cn[1] = (char)w_cn ;
}
//-------------------------------------------------------------------
//函数:ConvertWCHARToHex
//功能:将16位字符串转换为十六进制字符串
//参数:待转换的字符串,字符串长度
//返回值:转换后的字符串
//作者:chuchong
//-------------------------------------------------------------------
CString StyleConvert::ConvertWCHARToHex(CString Data, long nDataLength)
{
CString sResult("");
for (long nLoop=0; nLoop<nDataLength; nLoop++)
{
wchar_t ch = Data.GetAt(nLoop);
//将wchar_t转换为char[2]
char c_cn[2]={'0'};
W2C(ch,c_cn);
static const char *hex = "0123456789ABCDEF";
for(int i=0;i<2;i++)
{
unsigned char chHexA = hex[((unsigned char)(c_cn[i]) >> 4) & 0x0f];
unsigned char chHexB = hex[(unsigned char)(c_cn[i]) & 0x0f];
sResult += (char)chHexA;
sResult += (char)chHexB;
}
}
return sResult;
}