//==================================================================
/**
功能: 将16进制数组转换成asc字符数组(短转长)
@param[in] hex :要转换的十六进制数组
@param[in] lenth :转换后的16进制数组的长度
@param[out] asc :转换后的asc字符数组(至少分配2倍的hex的大小)
@par修改记录:
2015.01.15 马兆瑞 修改asc不为空时出现的bug
**/
//==================================================================
void hex2asc(unsigned char *hex, int hexlength, unsigned char *asc)
{
for(int i = 0; i < hexlength; i++)
{
sprintf((char*)asc+2*i, "%02X", hex[i]);
}
}
//==================================================================
/**
功能: 将asc字符数组转换成16进制数组(长转短),长度不足则末尾自动补F
@param[in] asc :要转换的asc字符数组
@param[in] lenth :转换后的16进制数组的长度
@param[out] hex :转换后的16进制数组
@par修改记录:
2015.12.22 马兆瑞
**/
//==================================================================
void asc2hex(unsigned char *asc, int hexlength, unsigned char *hex)
{
if(strlen((char*)asc) < hexlength*2)
{
char *asc_temp = new char[hexlength*2+1];
memset(asc_temp, 'F', hexlength*2+1);
memcpy(asc_temp, asc, strlen((char*)asc));
for(int i = 0; i < hexlength; i++)
{
char temp[3] = {asc_temp[i*2], asc_temp[i*2+1]};
hex[i] = strtol(temp, 0, 16);
}
delete []asc_temp;
}
else
{
for(int i = 0; i < hexlength; i++)
{
char temp[3] = {asc[i*2], asc[i*2+1]};
hex[i] = strtol(temp, 0, 16);
}
}
}
void main()
{
unsigned char asc[] = "915600000221010021010A68", hex[100] = {0};
asc2hex(asc, strlen((const char *)asc)/2 , hex);
unsigned char ascr[512] = {0};
hex2asc(hex, strlen((const char *)asc)/2 , ascr);
}