#include <stdio.h>
#include <string.h>
unsigned short hex_to_str(const unsigned char *hex, unsigned short hex_len, char *str,
unsigned short str_max)
{
int j = 0;
char ascii[] = "0123456789ABCDEF";
if ((hex == NULL) || (str == NULL))
return -1;
if (str_max < (2 * hex_len))
return -2;
memset(str, 0, str_max);
for (int i = 0; i < hex_len; i++, j += 2)
{
str[j] = ascii[(hex[i] & 0xF0) >> 4];
str[j + 1] = ascii[hex[i] & 0x0F];
}
return j;
}
unsigned short str_to_hex(const char *str, unsigned short str_len, unsigned char *hex,
unsigned short hex_max)
{
int i = 0;
if ((hex == NULL) || (str == NULL))
return -1;
if (hex_max < (str_len / 2))
return -2;
memset(hex, 0, hex_max);
for (int j = 0; j < str_len; i++, j += 2)
{
if (str[j] >= '0' && str[j] <= '9')
{
hex[i] = str[j] - '0';
}
else if (str[j] >= 'A' && str[j] <= 'F')
{
hex[i] = str[j] - 'A' + 10;
}
if (j + 1 >= str_len)
{
i++;
break;
}
if (str[j + 1] >= '0' && str[j + 1] <= '9')
{
hex[i] <<= 4;
hex[i] |= str[j + 1] - '0';
}
else if (str[j + 1] >= 'A' && str[j + 1] <= 'F')
{
hex[i] <<= 4;
hex[i] |= str[j + 1] - 'A' + 10;
}
}
return i;
}
示例:
int main()
{
unsigned char hex2[100] = {0x01, 0x1C, 0xA1, 0xEF, 0x61, 0x69, 0x64, 0x75};
char str2[100] = {0};
char str1[] = "011CA1EF";
unsigned char hex1[100] = {0};
int len2 = hex_to_str(hex2, 4, str2, 10);
printf("len2:%d,%s\r\n", len2, str2);
int len1 = str_to_hex(str1, 8, hex1, 100);
printf("len1:%d,%X %X %X %X\r\n", len1, hex1[0], hex1[1], hex1[2], hex1[3]);
return 0;
}
$main len2:8,011CA1EF len1:4,1 1C A1 EF
|