1. 十六进制char* 转 Binary char*
例如:“fedcba9876543210”
转换为:char bin[8] ={0xfe,0xdc,0xba,0x98,0x76,0x54,0x32,0x10}形式。
代码:
/*两个字符转换成一个字符,长度为原来的1/2*/
static void Hex2Char(char *szHex, unsigned char *rch)
{
int i;
for(i=0; i<2; i++)
{
if(*(szHex + i) >=‘0‘ && *(szHex + i) <= ‘9‘)
*rch = (*rch << 4) + (*(szHex + i) - ‘0‘);
else if(*(szHex + i) >=‘a‘ && *(szHex + i) <= ‘f‘)
*rch = (*rch << 4) + (*(szHex + i) - ‘a‘ + 10);
else
break;
}
}
/*十六进制char* 转 Binary char*函数*/
void HexStr2CharStr( char *pszHexStr, int iSize, char *pucCharStr)
{
int i;
unsigned char ch;
if (iSize%2 != 0) return;
for(i=0; i<iSize/2; i++)
{
Hex2Char(pszHexStr+2*i, &ch);
pucCharStr[i] = ch;
}
}
2. Binary char* 转 十六进制char*
例如:char bin[8] ={0xfe,0xdc,0xba,0x98,0x76,0x54,0x32,0x10};
转换为:“fedcba9876543210”
代码:
/*单个字符转十六进制字符串,长度增大2被*/
static void Char2Hex(unsigned char ch, char *szHex)
{
int i;
unsigned char byte[2];
byte[0] = ch/16;
byte[1] = ch%16;
for(i=0; i<2; i++)
{
if(byte[i] >= 0 && byte[i] <= 9)
szHex[i] = ‘0‘ + byte[i];
else
szHex[i] = ‘a‘ + byte[i] - 10;
}
szHex[2] = 0;
}
/*字符串转换函数,中间调用上面的函数*/
void CharStr2HexStr( char *pucCharStr, int iSize, char *pszHexStr)
{
int i;
char szHex[3];
pszHexStr[0] = 0;
for(i=0; i<iSize; i++)
{
Char2Hex(pucCharStr[i], szHex);
strcat(pszHexStr, szHex);
}
}
时间: 2024-11-15 01:02:40