Strange behaviour of 64 bit integer in C++

1.4k views Asked by At

I'm quite new to programming, I have recently learnt a little C++ and I am using Visual Studio 2017 Community version.

I need to use a 64 bit integer to store a value and carry out some arithmetic operations, however my compiler only allows me to use 32 bits of the "int64" variable I have created.

Here is an example of some code and the behaviour

    unsigned __int64  testInt = 0x0123456789ABCDEF;

printf("int value = %016X\n", testInt); // only 32 bits are being stored here? (4 bytes)

printf("size of integer in bytes = %i\n\n", sizeof(testInt)); // size of int is correct (8 bytes)

The value stored in the variable seems to be 0x0000000089ABCDEF. Why can I not use all 64 bits of this integer, it seems to act as a 32 bit int?

Probably I'm missing something basic, but I can't find anything relating to this from searching :(

2

There are 2 answers

2
Stephan Lechner On

Format specifier %X takes an unsigned int (probably 32 bit on your system), whereas __int64 corresponds to long long.

Use printf("int value = %016llX\n", testInt) instead. Documentation can be found, for example, at cppreference.com.

1
Myk Willis On

It would be nice if it were just something basic, but it turns out that 64 bit ints are not dealt with consistently on all platforms so we have to lean on macros.

This answer describes the use of PRIu64, PRIx64, and related macros included in <inttypes.h>. It looks funny like this, but I think the portable solution would look like:

#include <inttypes.h>
unsigned __int64  testInt = 0x0123456789ABCDEF;
printf("int value = %016" PRIX64 "\n", testInt);

The PRIX64 expands to the appropriate format specifier depending on your platform (probably llX for Visual Studio).