1

In c++ (Linux, without using boost).

I have 2 64 bits variables (long long) (say x and y).

when I'm doing x*y the result may be 128 bits. How can I store it ? is there a variable that define a 128 bits ?

(I need a specific variable of 128 bits, because later in my program I may use the "/" operations on that 128 bit variable )

Thank's

user3668129
  • 4,318
  • 6
  • 45
  • 87
  • What about using doubles? – ThreeFx Jun 10 '14 at 18:42
  • 1
    There should be some "infinite precision" (or "extended precision") packages floating around, that permit integers (and floats) wider than the hardware and native language support. It's software emulation, so it's slow, and you may not have literals that size. – Phil Perry Jun 10 '14 at 18:43
  • Looks like GCC still has an `int128_t` that should work from what I can tell. – chris Jun 10 '14 at 18:45
  • what are you doing that would require more than 64bit ints? check out https://gmplib.org/ – Aaron Oommen Jun 10 '14 at 18:48

1 Answers1

2

Try __int128 GCC extension:

#include <cstdio>

int main(void) {
    long long a, b, c;

    a = 9223372036854775807LL;
    b = 3;
    c = 5;

    __int128 r = (__int128) a * b;

    c = r / c;

    printf("%lld\n", c); // 5534023222112865484
}

Note that explicit cast is required for multiplication (i.e. to "force" __int128 type for operands). As long as you have 64-bit target it should work that way. To confirm check your result with e.g. bc:

$ echo "9223372036854775807*3/5" | bc
5534023222112865484

You might also try some arbitratry precision library like GMP.

Grzegorz Szpetkowski
  • 36,988
  • 6
  • 90
  • 137