VC++中字符串与⼗六进制互相转换//字符串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;
}
cstring转为intreturn result;
}
long CharToHex(long ch)
{
long la = (ch>=(long) 'A' ? (ch -(long) 'A' + 10) : (ch -(long) '0')); return la;
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论