Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to input int64_t / uint64_t constants?

What I'm trying to do is to define a constant equal to 2^30 (I may change it to something like 2^34, so I prefer to have a room larger than 32 bits for it).

Why the following minimal(?) example doesn't compile?

#include <stdint.h>
// test.cpp:4:33: error: expected primary-expression before numeric constant
// test.cpp:4:33: error: expected ')' before numeric constant
const uint64_t test = (uint64_t 1) << 30;
//const uint64_t test1 = (uint64_t(1)) << 30;// this one magically compiles! why?

int main() { return 0; }
like image 916
fiktor Avatar asked Mar 12 '14 20:03

fiktor


People also ask

What is uint64_t C?

The UInt64 value type represents unsigned integers with values ranging from 0 to 184,467,440,737,095,551,615. UInt64 provides methods to compare instances of this type, convert the value of an instance to its string representation, and convert the string representation of a number to an instance of this type.

What type is int64_t?

A long on some systems is 32 bits (same as an integer), the int64_t is defined as a 64 bit integer on all systems (otherwise known as a long long).


2 Answers

You can use the macro:

UINT64_C

to define a 64bit unsigned integer literal, the cstdint header provides macros for defining integer literals of specific sizes, we see that in section 18.4.1 Header synopsis:

The header also defines numerous macros of the form:

and includes:

plus function macros of the form:

[U]INT{8 16 32 64 MAX}_C

We have to go back to the C99 draft standard to find how they work, section 7.18.4.1 Macros for minimum-width integer constants which says:

[...]if uint_least64_t is a name for the type unsigned long long int, then UINT64_C(0x123) might expand to the integer constant 0x123ULL.

as the proper way of defining a 64bit integer constant expression. This is unfortunately not document on cpprefernce but cplusplus.com does document this feature for of the cstdint header as well as the posix reference for stdint.h.

like image 171
Shafik Yaghmour Avatar answered Oct 05 '22 15:10

Shafik Yaghmour


The syntax you are looking for is:

const uint64_t test = 1ULL << 30;

The post-fix ULL is used for unsigned integer literals that are at least 64-bits wide.

like image 44
Zac Howland Avatar answered Oct 05 '22 14:10

Zac Howland