Good day. There is a binary file, the information in which is presented in the form of hexadecimal octets. Let the content of the file be: "01 31 A4 F5". It is required to read the first two bytes, and then translate into a decimal number. I do it like this:
#include<stdio.h> #include<stdlib.h> int main() { FILE *ptrFile = fopen("/path/file.bin", "rb") int *num = (int *) malloc(2); //Π²ΡΠ΄Π΅Π»ΠΈΠ» Π² ΠΏΠ°ΠΌΡΡΠΈ 2 Π±Π°ΠΉΡΠ°, ΠΏΡΠΈΠ²Π΅Π» ΡΠΊΠ°Π·Π°ΡΠ΅Π»Ρ ΠΊ ΡΠΈΠΏΡ int fread(num, 1, 2, ptrFile); //ΡΡΠΈΡΡΠ²Π°Ρ ΠΈΠ· ΡΠ°ΠΉΠ»Π° 2 ΡΠ»Π΅ΠΌΠ΅Π½ΡΠ° ΡΠ°Π·ΠΌΠ΅ΡΠΎΠΌ 1 Π±Π°ΠΉΡ ΠΊΠ°ΠΆΠ΄ΡΠΉ Π² Π±Π»ΠΎΠΊ ΠΏΠ°ΠΌΡΡΠΈ num printf("hex num is %X\n", *num); //Π²ΡΠ²ΠΎΠ΄ ΡΡΠΈΡΠ°Π½Π½ΠΎΠΉ ΠΈΠ½ΡΡ Π² hex Π²ΠΈΠ΄Π΅ printf("dec num is %d\n", *num); //Π²ΡΠ²ΠΎΠ΄ ΡΡΠΈΡΠ°Π½Π½ΠΎΠΉ ΠΈΠ½ΡΡ Π² dec Π²ΠΈΠ΄Π΅ return 0; } As a result, instead of getting
hex num is 131 dec num is 305 I get:
hex num is 3101 dec num is 12545 Why does fread () invert bytes and how to avoid it?
fread()nothing to do with it, all due to the fact that x86 is a little-endian architecture, i.e. The lower digits of the number are in bytes with lower addresses. And we are used to writing numbers in big-endian (lower order on the right). Here you have a big-endian file. - avp