1

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

1 Answer 1

4

The file is being read correctly. On your system uint16_t is little-endian, i.e. 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.

Sign up to request clarification or add additional context in comments.

1 Comment

Oh, of course! Swapping the endianness resulted in the output I needed. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.