Search code examples
c++128-bit

wrong multiplication result for __uint128_t result


I want to multiple two 64 bits numbers and store their results into two 64 bits (total 128) bits variables

for this I wrote following simple function

void multiply2(uint64_t a, uint64_t b, uint64_t& hi, uint64_t& lo) {
__uint128_t product = static_cast<__uint128_t>(a) * static_cast<__uint128_t>(b);
hi = static_cast<uint64_t>(product >> 64);
lo = static_cast<uint64_t>(product);}}

and then I test is using following

int main(int argc, char* argv[]){

uint64_t a = 4539155444;
uint64_t b = 4539155444;
uint64_t hi, lo;
multiply1(a, b, hi, lo);
std::cout << a << " * " << b << " = " << hi << lo << std::endl;
return 0;}

The output I am getting is

4539155444 * 4539155444 = 12157188071085285520

But expected output is 4539155444 * 4539155444 = 20603932144794837136

I am confused what am I doing wrong here?


Solution

  • You cant simply take two parts of the number and print the next to each other and get the correct decimal number. You need to write your own function to print it.

    void printi128(__int128 val)
    {
        if(val < 10 && val > -10) printf("%d", val);
        else 
        {
            printi128(val / 10);
            printf("%d", abs(val % 10));
        }
    }
    

    https://godbolt.org/z/bTYsEbrsM