0

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?

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
CryptoKitty
  • 654
  • 4
  • 20
  • 1
    You can't just print out two decimal numbers next to each other and get a valid result (it would work in hex), you'll need to convert back to 128bit for printing, your answer is `1` and `2157188071085285520` which are the correct 64-bit numbers – Alan Birtles Apr 28 '23 at 07:20
  • It does not work like this. You can only print it this way using hexadecimal notation, but not a decimal number – 0___________ Apr 28 '23 at 07:20
  • ok let me try that – CryptoKitty Apr 28 '23 at 07:21
  • The split happens between two binary digits, not between two decimal digits. – BoP Apr 28 '23 at 07:21

1 Answers1

1

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

0___________
  • 60,014
  • 4
  • 34
  • 74