Bitshifting a uint64_t gives wrong result

142 Views Asked by At

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.

0

There are 0 best solutions below