简体   繁体   English

如何从C中的文本文件读取十六进制数据

[英]How to read a hex data from a text file in C

I am trying to read a text file with CAN data, the format the file is something like this : 我正在尝试读取具有CAN数据的文本文件,该文件的格式如下所示:

XL_CAN_EV_TAG_RX_OK ch:0 t=51165282304 id:98FF5C80 dlc:7 000000040000E0 XL_CAN_EV_TAG_RX_OK ch:0 t=51172728832 id:98FF1480 dlc:7 FFFFFFAD7C1CFF XL_CAN_EV_TAG_RX_OK ch:0 t=51173007360 id:98FF1080 dlc:7 FFFFE30C0E01FF XL_CAN_EV_TAG_RX_OK ch:0 t=51173285888 id:98FF1180 dlc:7 FFFF9706FEFFFB XL_CAN_EV_TAG_RX_OK ch:0 t=51173564416 id:98FF1280 dlc:7 FFFF9706FEFFFB XL_CAN_EV_TAG_RX_OK ch:0 t = 51165282304 id:98FF5C80 dlc:7 000000040000E0 XL_CAN_EV_TAG_RX_OK ch:0 t = 51172728832 id:98FF1480 dlc:7 FFFFFFAD7C1CFF XL_CAN_EV_TAG_RX_FF_7_FF51_FFF_7_FF51_FE_TAG_RX51_OK:00 FF:0C_FF_EFF_TAG_RX_OK_CH_F00:0173 = 1FF_CFF_EFF_TAG_RX51_OK_CFF:0173 :98FF1180 dlc:7 FFFF9706FEFFFB XL_CAN_EV_TAG_RX_OK ch:0 t = 51173564416 id:98FF1280 dlc:7 FFFF9706FEFFFB

I have to read the CANid and the the CANDATA as seen above, I managed to read the CANID using the : 我必须如上所述读取CANid和CANDATA,我设法使用读取了CANID:

unsigned int hex = 0; 
fscanf(fr, "%X", &hex); 
printf(" %X ", hex);

I use the c = fgetc(fr); 我使用c = fgetc(fr); till the c reads the second ":" and hex reads the canid fine. 直到c读取第二个“:”,十六进制读取犬科动物罚款。

But, when I have to read the data using the same code "fscaf", it only reads the last 7 data for example ,I get results like this : 但是,当我不得不使用相同的代码“ fscaf”读取数据时,例如,它仅读取最后7个数据,我得到如下结果:

40000e0 D7C1CFF C0E01FF 6FEFFFB 6FEFFFB

This is the problem. 这就是问题。 The alternative i found is to read it as char. 我发现的替代方法是将其读取为char。

If i use the getc to read, I get the data in char format, I am not sure how to convert that to a hex and also it reads each letter separately and I have to combine them and then convert it into an int type (hex) specifically and send it to a array, something like this: 如果我使用getc进行读取,则会以char格式获取数据,但我不确定如何将其转换为十六进制,并且它会分别读取每个字母,因此我必须将它们组合在一起,然后将其转换为int类型(十六进制) ),然后将其发送到数组,如下所示:

data[0]=FF; 数据[0] = FF; data[1]=FF; 数据[1] = FF; data[2]=FF; 数据[2] = FF; data[3]=AD; 数据[3] = AD; data[4]=7C; 数据[4] = 7C; data[5]=1C; 数据[5] = 1C; data[6]=FF; 数据[6] = FF;

I have been stuck here since two days, googled everything and tried everything, nothing seems to work, can you please help me with this. 自从两天以来,我一直被困在这里,用Google搜索一切,尝试了一切,似乎没有任何效果,请您帮我一下。 Thank you. 谢谢。

You're reading an unsigned int and storing into an unsigned int . 您正在读取unsigned int并将其存储到unsigned int unsigned int is 32 bits, your hex values are 7 bytes or 56 bits long. unsigned int是32位,您的十六进制值是7个字节或56位长。 You need a 64 bits container for those. 您需要一个64位的容器。 You'll want to use unsigned long long int and read/write them with %llX . 您将要使用unsigned long long int并使用%llX对其进行%llX

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM