CString字符串轉換為十六進制字符串

字號:

最近在做項目時遇到這個問題,比如將漢字“沖”轉換后為“51B2”,程序使用的是unicode字符集,下面是通過查資料后整理的解決方法:
    //-----------------------------------------
    //函數:W2C
    //功能:將16位wchar_t轉換為 8位char[2]
    //參數:w_cn為待轉換的16位字符,c_cn[]為轉換后的8位字符
    //備注:wchar_t的高位字節(jié)應該存儲在char數組的低位字節(jié)
    //-----------------------------------------
    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位字符串轉換為十六進制字符串
    //參數:待轉換的字符串,字符串長度
    //返回值:轉換后的字符串
    //-----------------------------------------
    CString StyleConvert::ConvertWCHARToHex(CString Data, long nDataLength)
    {
    CString sResult("");
    for (long nLoop=0; 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;
    }