将字符串转换为16进制的字符串(常用在串口编程中)

string StringToHex(LPCSTR lpSrc, char chTag = 0)
{//将字符串转换为16进制的字符串; chTag为分界符,如果为0x20表示空格
string strDest;
unsigned char* pSrc = (unsigned char*)lpSrc;
char  buf[2];
long dwSize = strlen(lpSrc);
for (long dwIndex = 0; dwIndex < dwSize; ++dwIndex)
{
unsigned char c0 = *pSrc >> 4;  
if ( c0 >= 0x0 && c0 <= 0x9)
{
buf[0] = c0 - 0 + '0';
}
else 
{
buf[0] = c0 - 10 + 'A';
}
unsigned char c1 = *pSrc++ & 0x0F;
if ( c1 >= 0x0 && c1 <= 0x9)
{
buf[1] = c1 - 0 + '0';
}
else 
{
buf[1] = c1 - 10 + 'A';
}
strDest += buf[0];
strDest += buf[1];
if (0 != chTag)  
strDest += chTag;
}
return strDest;
}

你可能感兴趣的:(MFC,C/C++)