1. 程式人生 > >VC++中字串與十六進位制互相轉換

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;
}
return result;
}

long CharToHex(long ch)
{
long la = (ch>=(long) 'A' ? (ch -(long) 'A' + 10) : (ch -(long) '0'));
return la;
}