0

As was said in the title, bitshifting a uint64_t type gives wrong results. I have absolutely no idea why this is the case. It seems like on the edges of the shifted bytes, it's modified the values to the the inverse of what they were originally.

An example:

#include <cstdint>
#include <fstream>
#include <iostream>
#include <bitset>

// Prints the binary representation of the given object
template<typename T>
void print_bin(const T& a)
{
    const char* beg = reinterpret_cast<const char*>(&a);
    const char* end = beg + sizeof(a);
    while (beg != end)
        std::cout << std::bitset<CHAR_BIT>(*beg++) << ' ';
}

int main()
{
    uint64_t notBitshifted = 0b0000000000000000000000000001111111111111111001000000000000001000;

    std::ofstream outfile("out.bin", std::ios::binary | std::ios::out);

    uint64_t bitshifted = notBitshifted << static_cast<uint64_t>(1);

    outfile.write(reinterpret_cast<const char*>(&bitshifted), sizeof(bitshifted));
    
    outfile.close();

    std::ifstream file("out.bin", std::ios_base::binary);

    while (file)
    {
        char byte;
        file.get(byte);
        print_bin(byte);
    }
}

The results & the expected results:

Where:

notBitshifted is: 0000000000000000000000000001111111111111111001000000000000001000
bitshifted is:    0000000000000000000000000011111011111110110010010000000100010000

bitshifted is clearly not notBitshifted shifted to the left 1. This doesn't make any sense to me.

NickKnack
  • 119
  • 1
  • 8
  • 1
    I suspect the problem is with the I/O, and not the result. – tucuxi Apr 16 '22 at 19:08
  • Unable to reproduce. The output is exactly as I would expect: `0000000000000000000000000011111111111111110010000000000000010000` http://coliru.stacked-crooked.com/a/21941990163091a6 – eerorika Apr 16 '22 at 19:22
  • 3
    Likely you are on a *little endian* machine, and are not taking into account the bytes are not in big-to-little order, even if the bits are in big-to-little order. – Eljay Apr 16 '22 at 19:32

0 Answers0