使用C代码实现读取文件中的hex字符串,转换为字节数组
举例说明:
ptp.txt文件中的内容为:
7a7ac0a8c80100000000003388f70002002c00000400000000000000000000000000000000000000000000000000000011111100000000000000
解析之后为:
7a 7a c0 a8 c8 01 00 00 00 00 00 33 88 f7 00 02
00 2c 00 00 04 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
11 11 11 00 00 00 00 00 00 00
下面给出实现的代码:
#include <stdio.h>
#include <stddef.h>
#define PKT_ARRAY_SIZE 512
#define uint8_t unsigned char
#define uint16_t unsigned short
static int chartoint(char ch)
{
if(ch >= '0' && ch <= '9')
return ch-'0';
if(ch >= 'A' && ch <= 'F')
return ch - 'A' + 10;
if(ch >= 'a' && ch <= 'f')
return ch - 'a' + 10;
printf("Warrning: Data is wrong. %x\n", ch);
return -1;
}
static void get_hex_array_from_file(char *pkt_name, uint8_t pkt_array[PKT_ARRAY_SIZE], uint16_t *total_bytes)
{
FILE *fp = NULL;
char c;
int i = 0;
uint8_t tmp0 = 0, tmp1 = 0;
uint16_t index = 0;
fp = fopen(pkt_name, "r");
if (fp == NULL) {
printf("can not open %s\n", pkt_name);
return;
}
while (1) {
c = fgetc(fp);
if (feof(fp) || c == 0xa) { //换行符
if (i % 2 == 1) {
pkt_array[index] = tmp0 & 0xFF;
*total_bytes += 1;
}
break;
}
i += 1;
if (i % 2 == 1) {
tmp0 = chartoint(c);
}
if (i % 2 == 0) {
tmp1 = chartoint(c);
pkt_array[index] = ((tmp0 << 4) + tmp1) & 0xFF;
index += 1;
tmp0 = 0;
tmp1 = 0;
}
}
*total_bytes = index;
fclose(fp);
}
int main(void)
{
uint8_t pkt_array[PKT_ARRAY_SIZE] = {0};
uint16_t total_bytes = 0;
uint16_t i = 0;
char *pkt_name = "ptp.txt";
get_hex_array_from_file(pkt_name, pkt_array, &total_bytes);
printf("total_bytes:%d\n", total_bytes);
for (i = 1; i <= total_bytes; i++) {
printf("%02x ", pkt_array[i-1]);
if (i % 16 == 0)
printf("\n");
}
printf("\n");
return 0;
}
编译运行: