C ++ weird behavior when reading binary ifstream

For my first question here, I would like to talk about reading binaries in C ++; I am rewriting the ID3 tag library.

I am parsing the header, which is a binary file, the first 10 bytes are as follows:

ID3    = 3 bytes = constant identifier
0xXXXX = 2 bytes = version (MSB: major version, LSB: minor. eg: 0x0301 = v3.1)
0xXX   = 1 byte  = some flags
4*0xXX = 4 bytes = size

here is the code snippet for processing:

char          id[4];
uint16_t      version;
uint8_t       flags;
uint32_t      size;
std::ifstream _stream;

_stream = std::ifstream(_filename, std::fstream::binary);

_stream.read(id, 3);
id[3] = 0;
// process id
_stream.read((char *)&version, 2);
// process version
_stream.read((char *)&flags, 1);
// process flags
_stream.read((char* )&size, 4);
// process flags
_stream.close();

everything works fine except for the version. let's say v3.0 (0x0300), the value set in the version is 0x03, I would understand this behavior in text mode, since it would consider 0x00 as the end of the line, but here I read in binary format. And use number formats.

Another strange thing, if I process it 2 times, I can make it work, for example:

uint16_t version = 0;
char     buff;

 _stream.read(&buff, 1);
version = (buff << 8);
 _stream.read(&buff, 1);
version |= buff;

In this case, the version value is 0x0300.

Do you have an idea why the first method does not work correctly? Am I doing something wrong?

, ,

!

+4
2

unsigned short, ( , ). , endianess.

Endianess . , , . , .

+4

. ? Wikipedia:

Endianness , ,

:

big-little-endian

, , , - , , , .

, , :

  • .
  • _byteswap_ushort V++ __builtin_bswap16 GCC
+1

Source: https://habr.com/ru/post/1686804/


All Articles