Home c Fread () on C - Inversion bytes

Fread () on C – Inversion bytes




Good afternoon. There is a binary file, information in which is presented in the form of hexadecimal octets. Let the content of the file: “01 31 A4 F5”. It is required to be considered the first two bytes, and then translate into a decimal number. I do it like this:

# include & lt; stdio.h & gt;
# INCLUDE & LT; stdlib.h & gt;
File * ptrfile = Fopen ("/ path / file.bin", "rb")
int * num = (int *) malloc (2); // highlighted in memory 2 bytes, led the pointer to the type int
Fread (Num, 1, 2, Ptrfile); // read from the file 2 element size 1 byte each in the NUM memory unit
PrintF ("HEX NUM IS% X \ N", * NUM); // withdrawal information in hex form
PrintF ("Dec Num IS% D \ N", * Num); // Conclusion of a read info in the DEC form
Return 0;

As a result, instead of getting

hex num is 131

I get:

hex num IS 3101
DEC NUM IS 12545

Why did Fread () invert bytes and how to avoid?

Answer 1, Authority 100%

First, you highlight the memory of 2 bytes, and read the SizeOf (int) byte, and this is usually 4, but maybe another number – the Int size in the language is not fixed. Those. You read for the allocated memory, this is a mistake.

Secondly, read about Little Endian (LE) and Big Endian (BE) – two different ways of representing numbers in memory. On the X86 architecture, it is always le, so first the junior byte goes first. This explains why the bytes you have “turned over” when displaying on the screen (although in memory they are in the same order).

” Byte order “in Wikipedia

about “how to avoid it” – it depends on what you want to get. If the goal is to show what is in the file – read the byte array and output bytes for the byte.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions