Suman Raj
Suman Raj

Reputation: 41

Why does a long long int have the wrong value when initialized with a huge integer literal?

I am trying to store 10000000000000000000 (1019) inside a long long int.

#if __WORDSIZE == 64
typedef long long int       intmaximum_t;
#else
__extension__
typedef unsigned long int   intmaximum_t;
#endif

const intmaximum_t  = 10000000000000000000;

But it is giving output -8446744073709551616.

I have a 64-bit machine running Ubuntu. How do I store this value?

Upvotes: 1

Views: 1216

Answers (2)

Bathsheba
Bathsheba

Reputation: 234875

The largest possible value for a 64 bit long long int is 9,223,372,036,854,775,807. Your number is bigger than that. (Note that this number less the one you get is one off the number you actually want - that's not a coincidence but a property of 2's complement arithmetic).

It would fit in an unsigned long long int, but if you need an unsigned type you'll need to use a large number library for your number, or int128_t if your compiler supports it.

Upvotes: 4

dbush
dbush

Reputation: 225507

The value 10000000000000000000 is too large to fit in a signed 64-bit integer but will fit in an unsigned 64-bit integer. So when you attempt to assign the value it gets converted in an implementation defined way (typically by just assigning the binary representation directly), and it prints as negative because you are most likely using %d or %ld as your format specifier.

You need to declare your variable as unsigned long long and print it with the %llu format specifier.

unsigned long long x = 10000000000000000000;
printf("x=%llun", x);

Upvotes: 2

Related Questions