c++ 中文和十六进制的互转
CString CHexAndStrDlg::StrToHex(CString strData) { //初始化 CString strTemp =""; int iLenth = strData.GetLength(); char cArrData[512]; char cArrTemp[512]; memset(cArrData, 0, iLenth+1); memset(cArrTemp, 0, iLenth +1); memcpy(cArrData, strData, iLenth); cArrData[iLenth] =0; for(int i = 0; i< strlen(cArrData) ; i++) { if(cArrData[i] == 0) { break; } sprintf(cArrTemp + i*2,"%02X",(unsigned char)cArrData[i]); } setlocale(LC_ALL,"chs"); strTemp.Format("%s", cArrTemp); return strTemp; }
CString CHexAndStrDlg::HexToStr(CString strHex) { CString strTemp =""; int iLenth = strHex.GetLength(); char *cArrData = new char[iLenth + 1]; char *cArrTemp = new char[iLenth + 1]; memset(cArrData, 0, strHex.GetLength()); memset(cArrTemp, 0, strHex.GetLength()); memcpy(cArrData,strHex, strHex.GetLength()); cArrData[iLenth] = 0; int i=0; int iOcx; for(int i = 0; i< iLenth /2 ;i++) { if (1!=sscanf(cArrData+i*2,"%2x",&iOcx)) break; cArrTemp[i]=(char)iOcx; } //cArrTemp[iLenth/2]=0; strTemp.Format("%s", cArrTemp); delete cArrTemp; delete cArrData; if( cArrData != NULL) cArrData = NULL; if( cArrTemp != NULL) cArrData = NULL; return strTemp; }
CString strTemp = StrToHex("12345ABCDefg:$%^^^^我们都一样");
结果: 3132333435414243446566673A3A3A3A2523CED2C3C7B6BCD2BBD1F9
strTemp = HexToStr(strTemp);
结果:12345ABCDefg:$%^^^^我们都一样
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。