简体   繁体   中英

Binary file read different results for amount of bytes read at a time

I am reading binary data from a file, however reading one byte at a time gives expected results, while reading anymore than one byte at a time does not. Reading one at a time:

void readFile(){
        std::ifstream in;
        in.open("file.bin", std::ios:binary);

        uint8_t byte1;
        uint8_t byte2;
        in.read(reinterpret_cast<char *>(&byte1), sizeof(byte1));
        in.read(reinterpret_cast<char *>(&byte2), sizeof(byte2));

        std::cout << std::bitset<8>(byte1) << std::bitset<8>(byte2);
}

This produces the expected output of

0000101000000110

Reading two at a time:

void readFile(){
        std::ifstream in;
        in.open("file.bin", std::ios:binary);

        uint16_t twobytes;
        in.read(reinterpret_cast<char *>(&twobytes), sizeof(twobytes));

        std::cout << std::bitset<16>(twobytes);
}

Produces unexpected output of

0000011000001010

The file is being read correctly. On your system uint16_t is little-endian, ie the lower 8 bits are stored in the first byte and the upper 8 bits are stored in the second byte, so the first byte read from the file becomes the lower 8 bits of the bitset (bits 0-7) and the second byte becomes the upper 8 bits (bits 8-15). When the bitset is printed, the bits are printed in order, from bit 15 down to bit 0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM