/*
十六进制数据改写为C语言数组形式
如:
0111
022222
03333333
生成:
{0x01,0x11},
{0x02,0x22,0x22},
{0x03,0x33,0x33,0x33},
如果第一个数为数据长度信息,第二个数为地址,其他为数据
如:
0111
022222
03333333
生成:
{0x01,0x01,0x11},
{0x02,0x02,0x22,0x22},
{0x03,0x03,0x33,0x33,0x33},
*/
#include <stdio.h>
#include <string.h>
int main(void)
{
FILE *fp = NULL;
int count = 0;
int num = 0;
int num2 = 0;
int num3 = 0;
int num4 = 0;
char buf[16000] = {}; //存储原来的数据
char buf2[16000] = {}; //原来的数据加上每行的数据个数
char result[16000] = {}; //改写为C语言数组形式。
fp = fopen("str.txt", "r");
if (fp == NULL) {
printf("open str.txt err!\n");
return -1;
}
count = fread(buf, sizeof(char), sizeof(buf), fp);
printf("read %d bytes\n", count);
if (count < 0) {
printf("read err!\n");
return -1;
}
fclose(fp);
/* 每行前面两个数据为该行有效16进制数据的长度,不需要长度信息,可以把下面这段屏蔽掉 */
#if 1
num2 += 2;
num3 = 0;
while(num < count) {
while(buf[num] != '\n') {
buf2[num2] = buf[num];
num2++;
num++;
}
if (buf[num] == '\n') {
buf2[num2] = buf[num];
num4 = (num2 - num3 - 1) / 2 - 1;
if (num4 / 16 >= 10)
buf2[num3] = num4 / 16 % 10 + 'A';
else
buf2[num3] = num4 / 16 + '0';
if (num4 % 16 >= 10)
buf2[num3+1] = num4 % 16 % 10 + 'A';
else
buf2[num3+1] = num4 % 16 + '0';
printf("num=%d, num2=%d, num3=%d, num4=%d\n", num, num2, num3, num4);
num3 = num2 + 1;
num2 += 3;
num++;
}
}
memset(buf, 0, sizeof(buf));
memcpy(buf, buf2, sizeof(buf));
printf("buf = %s\n", buf);
count = num2;
num = 0;
num2 = 0;
num3 = 0;
num4 = 0;
#endif
result[0] = '{';
result[1] = '0';
result[2] = 'x';
num2 = 3;
while (num < count) {
num3++;
if (buf[num] == '\n') {
num3 = 0;
result[num2++] = '}';
result[num2++] = ',';
result[num2++] = buf[num];
result[num2++] = '{';
result[num2++] = '0';
result[num2++] = 'x';
num++;
continue;
}
if (num3 <= 2) {
result[num2++] = buf[num];
}
if (num3 == 2) {
if (buf[num+1] != '\n') {
result[num2++] = ',';
result[num2++] = '0';
result[num2++] = 'x';
}
num3 = 0;
}
num++;
}
fp = fopen("result.txt", "w+");
if (fp == NULL) {
printf("open result.txt err!\n");
return -1;
}
count = fwrite(result, 1, num2+1, fp);
printf("write %d bytes\n", count);
if (count < 0) {
printf("write result.txt err!\n");
return -1;
}
fclose(fp);
return 0;
}
|