c++winapireadfilecl

Why doesn't Win32 ReadFile() preserve order of bytes when written to a uint16_t array buffer


I have a binary file, with the following data:

00e0 a248 6000 611e 6200 d202 d212 7208
3240 120a 6000 613e 6202 a24a d02e d12e
...

When I use ReadFile() and set the target buffer to a uint8_t array, the written buffer data matches the source file data:

uint8_t rom[256];
ReadFile(_, rom, _, NULL, NULL);
// in rom
rom[0x00000000] 0x00
rom[0x00000001] 0xe0
rom[0x00000002] 0xa2
rom[0x00000003] 0x48
rom[0x00000004] 0x60
rom[0x00000005] 0x00
rom[0x00000006] 0x61
...

Why is it when I use ReadFile() with a uint16_t array, each element has the bytes written in backwards?

uint16_t rom[256];
ReadFile(_, rom, _, NULL, NULL);
// in rom
rom[0x00000000] 0xe000
rom[0x00000001] 0x48a2
rom[0x00000002] 0x0060
rom[0x00000003] 0x1e61
rom[0x00000004] 0x0062
rom[0x00000005] 0x02d2
rom[0x00000006] 0x12d2
...

The same pattern seems to exist with larger types as well:

uint32_t rom[256];
ReadFile(_, rom, _, NULL, NULL);
// in rom
rom[0x00000000] 0x48a2e000
rom[0x00000001] 0x1e610060
rom[0x00000002] 0x02d20062
rom[0x00000003] 0x087212d2
rom[0x00000004] 0x0a124032
rom[0x00000005] 0x3e610060
rom[0x00000006] 0x4aa20262
...

the documentation for ReadFile() doesn't seem to mention anything about this behavior


Solution

  • ReadFile() has no concept of the kind of buffer you are reading into. It only reads raw bytes. And it does preserve the order of the bytes.

    Multi-byte integers (uint16_t is 2 bytes, uint32_t is 4 bytes) are subject to endian (ie, byte order), that is what you are experiencing. The bytes themselves are not being reversed. The values of the integers depend on the order in which the bytes are interpreted. The same byte sequence can represent different numeric values depending on whether the bytes are interpreted in little endian or big endian byte order.

    For example, the 2-byte sequence 00 e0 represents a uint16_t value of 53744 (hex 0xE000) in little endian, and of 224 (hex 0x00E0) in big endian.