Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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) printf("%d", val);
    else 
    {
        printi128(val / 10);
        printf("%d", abs(val % 10));
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading