Search code examples
c++bit-manipulation

Are bitwise operator working on __int128 in c++


I'm working on a project where I have to transform a __int128 into a vector of uint8_t.
I have already a function that transform a long into a vector of uint8_t.
I wanted to do something like :

__int128 data = 0x5bc5ddd975d34ed0b4f18b410e7d2480
addLong(data >> 64);
addLong(data & 0xFFFFFFFFFFFFFFFF);

and I'm getting this as a result : 00000000b4f18b41e7d2480
As you can see, the second part, the 64 less significant bytes are correctly treated, but the most ones aren't. Do you know if this is possible ?

Doing something like that :

std::cout << std::hex << (long)(data >> 48) << std::endl;

gives me the result : b4f1.
That's why I think bitwise operator aren't working with __int128.


Solution

  • The bitwise operators work, but your initialization does not. The integer literal can't be bigger than a long long.

    I suggest adding a helper function for the initialization (if there isn't already one in gcc):

    #include <cstdint>
    #include <iostream>
    
    __int128 init_int128(std::int64_t high, std::uint64_t low) {
        return __int128(high) << 64 | low;
    }
    
    int main() {
        __int128 data = init_int128(0x5bc5ddd975d34ed0, 0xb4f18b410e7d2480);
    
        std::cout << std::hex;
        std::cout << static_cast<std::int64_t>(data >> 64) << '\n';
        std::cout << static_cast<std::uint64_t>(data) << '\n';
    }
    

    Output

    5bc5ddd975d34ed0
    b4f18b410e7d2480