简体   繁体   中英

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 :

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

I have to read the CANid and the the CANDATA as seen above, I managed to read the CANID using the :

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

I use the c = fgetc(fr); till the c reads the second ":" and hex reads the canid fine.

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 :

40000e0 D7C1CFF C0E01FF 6FEFFFB 6FEFFFB

This is the problem. The alternative i found is to read it as 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:

data[0]=FF; data[1]=FF; data[2]=FF; data[3]=AD; data[4]=7C; data[5]=1C; data[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. Thank you.

You're reading an unsigned int and storing into an unsigned int . unsigned int is 32 bits, your hex values are 7 bytes or 56 bits long. You need a 64 bits container for those. You'll want to use unsigned long long int and read/write them with %llX .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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