shuttle87
shuttle87

Reputation: 15924

c++ cross platform way to define 64bit unsigned integer

Right now I'm working on a project that extensively uses 64bit unsigned integers in many parts of the code. So far we have only been compiling with gcc 4.6 but we are now porting some code to windows. It's crucial that these unsigned ints are 64bits wide. It has been suggested that we could use long long but it's not good if long long happens to be bigger than 64bits, we actually want to have a guarantee that it will be 64 bits and writing something like static_assert(sizeof(long long) == 8) seems to be a bit of a code smell.

What is the best way to define something like uint64 that will compile across both gcc and msvc without needing to have different code syntax used everywhere?

Upvotes: 5

Views: 3303

Answers (4)

Rafael Baptista
Rafael Baptista

Reputation: 11499

This is what I do:

#ifndef u64
#ifdef WIN32
typedef unsigned __int64   u64;
#else // !WIN32
typedef unsigned long long u64;
#endif
#endif

Upvotes: 1

Ajay
Ajay

Reputation: 18411

On Windows you can use __int64, unsigned __int64, or typedefs: UINT64, INT64 etc.

Look at this

But yes, if code portability is concern, use standard typedefs, as suggested by others.

Upvotes: 0

psur
psur

Reputation: 4519

You can use boost:

The typedef int#_t, with # replaced by the width, designates a signed integer type of exactly # bits; for example int8_t denotes an 8-bit signed integer type. Similarly, the typedef uint#_t designates an unsigned integer type of exactly # bits.

See: http://www.boost.org/doc/libs/1_48_0/libs/integer/doc/html/boost_integer/cstdint.html

Especially this header: http://www.boost.org/doc/libs/1_48_0/boost/cstdint.hpp

Upvotes: 3

Inbae Jeong
Inbae Jeong

Reputation: 4103

What about including cstdint and using std::uint64_t?

Upvotes: 15

Related Questions