16进制串与ASCII字符串相互转换
提供两个函数,方便十六进制串与ASCII 字符串之间的相互转换,使用函数需要注意的是返回的串是在堆上通过 calloc 分配的,所以,记得使用完返回值释放该块,并且将指向该块的指针 =NULL 。
// 函数输入字符串,输出字符串对应的16进制串
char *chstohex ( char* chs )
{
char hex[16] = { '0', '1', '2', '3', '4', '5', '6', \
'7', '8','9', 'A', 'B', 'C', 'D', 'E', 'F'
};
int len = strlen ( chs );
char* ascii = NULL ;
ascii = (char*)calloc ( len * 3 + 1, sizeof(char) ); // calloc ascii
int i = 0;
while( i < len )
{
ascii[i*2] = hex[(int)( (char)chs[i] / 16 )] ;
ascii[i*2 + 1] = hex[(int)( (char)chs[i] % 16 )] ;
++i;
}
return ascii; // ascii 返回之前未释放
}
// 函数输入16进制字符串,输出对应的字符串
char *hextochs ( char* ascii )
{
int len = strlen ( ascii ) ;
if( len%2 != 0 )
return NULL ;
char *chs = NULL ;
chs = (char*)calloc( len / 2 + 1, sizeof(char) ); // calloc chs
int i = 0 ;
char ch[2] = {0};
while( i < len )
{
ch[0] = ( (int)ascii[i] > 64 ) ? ( ascii[i]%16 + 9 ) : ascii[i]%16 ;
ch[1] = ( (int)ascii[i + 1] > 64 ) ? ( ascii[i + 1]%16 + 9 ) : ascii[i + 1]%16 ;
chs[i/2] = (char)( ch[0]*16 + ch[1] );
i += 2;
}
return chs ; // chs 返回前未释放
}
以上转自:http://blog.163.com/163_dhbing/blog/static/11738780320091086511358/
/*
字符串转16进制
*/
void StrToHex(BYTE *pbDest, BYTE *pbSrc, int nLen)
{
char ddl,ddh;
int i;
for (i=0; i<nLen; i++)
{
ddh = 48 + pbSrc[i] / 16;
ddl = 48 + pbSrc[i] % 16;
if (ddh > 57) ddh = ddh + 7;
if (ddl > 57) ddl = ddl + 7;
pbDest[i*2] = ddh;
pbDest[i*2+1] = ddl;
}
pbDest[nLen*2] = '\0';
}