http://hi.baidu.com/kenshin1987/blog/item/300b6be699487d26b83820ee.html
//解析二进制字符串
bool ParseBinStr(const char szStr[8], char* cpRst)
{
char cRtn = '\0';
if (szStr == NULL) return false;
for (int i=0; i<8; i++)
{
if (szStr != '0' && szStr != '1') return false;
cRtn = szStr - 48;
cRtn = cRtn << (8 - i - 1);
*cpRst |= cRtn;
}
return true;
}
//解析十六进制字符串
bool ParseHexStr(const char szStr[2],char* cpRst)
{
char cRtn = '\0';
if(szStr == NULL) return false;
//写高四位
if( ('0' <= szStr[0]) && ('9' >= szStr[0]) )
{
cRtn = (szStr[0] & 0x0F) << 4;
}
else if( ('A' <= szStr[0]) && ('F' >= szStr[0]) )
{
cRtn= (szStr[0] - 'A' + 10) << 4;
}
else if( ('a' <= szStr[0]) && ('f' >= szStr[0]) )
{
cRtn= (szStr[0] - 'a' + 10) << 4;
}
//写低四位
if( ('0' <= szStr[1]) && ('9' >= szStr[1]) )
{
cRtn += (szStr[1] & 0x0F);
}
else if( ('A' <= szStr[1]) && ('F' >= szStr[1]) )
{
cRtn += (szStr[1] - 'A' + 10);
}
else if( ('a' <= szStr[1]) && ('f' >= szStr[1]) )
{
cRtn += (szStr[1] - 'a' + 10);
}
*cpRst=cRtn;
return true;
}
http://hi.baidu.com/minmin283517/blog/item/0a475f435f6c651a72f05d60.html
int Ascii2Hex(const char *hex,char * ascii) //16进制转ASCII
{
int len = strlen(hex), tlen, i, cnt;
for (i = 0, cnt = 0, tlen = 0; i<len; i++)
{
char c = toupper(hex);
if ((c>='0'&& c<='9') || (c>='A'&& c<='F'))
{
BYTE t = (c >= 'A') ? c - 'A' + 10 : c - '0';
if (cnt)
ascii[tlen++] += t, cnt = 0;
else
ascii[tlen] = t << 4, cnt = 1;
}
}
return tlen;
}
int Ascii2Hex(char* ascii, char* hex) //ASCII 转16进制
{
int i, len = strlen(ascii);
char chHex[] = "0123456789ABCDEF";
for (i = 0; i<len; i++)
{
hex[i*3] = chHex[((BYTE)ascii) >> 4];
hex[i*3 +1] = chHex[((BYTE)ascii) & 0xf];
hex[i*3 +2] = ' ';
}
hex[len * 3] = '\0';
return len * 3;
}
看一下数字字符Ascii码值的规律就清楚了。
‘0’-‘9’对应0x30-0x39
‘A’-‘F’对应0x37-0x42
所以如果是十进制码转Ascii,加0x30就可以了
如果是十六进制码转Ascii,判断一下,小于9的加0x30,大于的加37
注意被转换的数要保证合法,即<=9或<=0x0F
u08 Hex_to_Ascii( u08 hex )
{
// hex转ascii
if ( hex <= 0x09 )
{
// 字符0-9 转换
return hex+0x30;
}
else
{
// 字符A-F 转换
return hex+0x37;
}
}
文章评论(0条评论)
登录后参与讨论