您的位置:首页 > 其它

字符串与十六进制互相转换 vc

2009-06-15 11:07 190 查看
//字符串CString 转换成CString类型的十六进制串

**********************************************************************************

CString ConvertCStringoHex(CString Data)
{
//CString转换成char[]
wchar_t* a=Data.GetBuffer( Data.GetLength() );
int nLen = WideCharToMultiByte( CP_ACP, 0, a, -1, NULL, 0, NULL, NULL );
if (nLen == 0)
{
return NULL;
}
char* pResult = new char[nLen];
char tagChar[2048];
WideCharToMultiByte( CP_ACP, 0, a, -1, pResult, nLen, NULL, NULL );
strncpy( tagChar,pResult , sizeof(tagChar));
//转换成hex
CString sResult=L"";
int nLoop=0;
while(tagChar[nLoop]!='/0')
{
static const char *hex="0123456789ABCDEF";
if(tagChar[nLoop]<127&&tagChar[nLoop]>0)
{
sResult += '0';
sResult += '0';
unsigned char chHexA = hex[((unsigned char)(tagChar[nLoop]) >> 4) & 0x0f];
unsigned char chHexB = hex[(unsigned char)(tagChar[nLoop]) & 0x0f];
sResult += (char)chHexA;
sResult += (char)chHexB;
nLoop++;
}
else
{
unsigned char chHexA = hex[((unsigned char)(tagChar[nLoop]) >> 4) & 0x0f];
unsigned char chHexB = hex[(unsigned char)(tagChar[nLoop]) & 0x0f];
sResult += (char)chHexA;
sResult += (char)chHexB;

if(tagChar[++nLoop]=='/0') break;
sResult+= hex[((unsigned char)(tagChar[nLoop]) >> 4) & 0x0f];
sResult+=hex[(unsigned char)(tagChar[nLoop]) & 0x0f];
nLoop++;

}
}
return sResult;

}

*********************************************************************************

//十六进制转CString字符串(包括汉字)

CString ConvertHextoCString(CString hex)
{
CString result=_T("");

char temp[3];
int i=0;
if(hex.GetLength()%4!=0)
{
return _T("");
}
int lenhex=hex.GetLength();
while(i<lenhex)
{
long h4 = CharToHex((long)hex.GetAt(i));
long h3 = CharToHex((long)hex.GetAt(i+1));

long h2 = CharToHex((long)hex.GetAt(i+2));
long h1 = CharToHex((long)hex.GetAt(i+3));

long t1=h4*16+h3;
long t2=h2*16+h1;
if(t1==0)
{
temp[0]=t2;
temp[1]='/0';
}
else
{
temp[0]=t1;
temp[1]=t2;
temp[2]='/0';
}
i+=4;
result+=temp;
}
return result;
}

long CharToHex(long ch)
{
long la = (ch>=(long) 'A' ? (ch -(long) 'A' + 10) : (ch -(long) '0'));
return la;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: