Unsigned long long vs unsigned long (portability point)

I want to use large positive integers (8 bytes) in my project, although sizeof (unsigned long) gives 8 on my system, I read that on most systems unsigned long there are only 4 bytes, and I decided to give unsigned long long a go, since it must be at least 8 bytes.

The more I use it, the more I saw that it is not very portable, for example, on some systems (depending on the compiler) printf formats it with% llu, in some it formats it with% lld.

My code will only work on 64-bit debian machines, in which the unsigned long will be 8 bytes. Portability is not a big problem. Is there an excessive use of unsigned long long unsigned long in these circumstances, are there other benefits to using unsigned long long over unsigned long?

+5
source share
3 answers

unsigned long longguaranteed at least 64 bits, regardless of platform. (There are platforms where it is more, I know 72 bits and 96 bits, but they are rare and clearly exotic.) unsigned longGuaranteed to be at least 32 bits. If you need more than 32 bits, I would recommend unsigned long long.

As for formatting, printfyou should use with "%llu"(since it is unsigned); "%lld"for signed long long.

+9

, , , boost:: integers (. ). boost:: int64_t boost:: uint64_t

0

, :

#include <limits.h>
#if ULONG_MAX >= 0xFFFFFFFFFFFFFFFFULL
typedef unsigned long uint64;
#else
typedef unsigned long long uint64;
#endif

W.r.t.

( ) printf % llu, % lld

printf() . .

a uint64, , :

printf("%llu", (unsigned long long)some_uint64_value);

typedef unsigned long long ulonglong; .

There are other ways to do the same, but not all compilers support them. That's why I attached the suffix ULLto a number. In some compatibility modes between C89 and C99, 0xFFFFFFFFFFFFFFFFFF can be interpreted as unsigned long, rather than unsigned long long, and will be truncated. The latest gcc works by default in mode gnu89for C code, not c99or higher.

0
source

All Articles