How to read two bytes of number?

Please explain how to implement the read (in SI):
a binary file with the following content:
00 01 00 00 00 01
The first two bytes is a whole number not exceeding 2000, and then go the whole 32 bit number (all big-endian).

Can't figure how to count these numbers, trying to make using fread, but it displays bogus numbers.

Thanks in advance!
June 10th 19 at 14:26
3 answers
June 10th 19 at 14:28
for 32-bit something like this. it is necessary to read bytes and deploy them (you're on x86 the program doing? it is little endian).
unsigned int ReadBig32(FILE * in_file)
 unsigned char temp[4];
 fread(temp, 1, 4, in_file);
 unsigned int result = temp[3] | (temp[2] << 8) | (temp[1] << 16) | (temp[0] << 24);
 return result;
June 10th 19 at 14:30
Code to write lazily, describe that
Numbers are stored (on regular x86), "backwards". That is, if number - int (32-bit) - it will occupy 4 bytes, with the most significant byte will be "the tail". For example - there is a buffer containing 01 02 03 04, hex of course (Your example fails). If the buffer is int what is the number? Right 0x04030201.
Therefore, anything anywhere most it magic With arithmetic!
tydedef struct {
short int a;
int b;
} wrk_buf;

wrk_buf my_buf;
read(desc, (void *) &my_buf, 1000);

Then you can simply access the fields of a structure as ordinary variables. It is clear that the file must first be open to its size - 1000 is the conventional number.
June 10th 19 at 14:32
Beautiful and versatile in any way, the most compatible method like this:

#include <stdint.h>
#if defined (__WIN32__)
#include <winsock2.h>
#include <arpa inet.h>

uint16_t read_16(FILE * f)
 uint16_t ui16;
 fread(&ui16, 1, 2, f);
 return, the(ui16);

uint32_t read_32(FILE * f)
 uint32_t ui32;
 fread(&ui32, 1, 4, f);
 return ntohl(ui32);

Find more questions by tags CC++Programming