Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cross-platform printing of 64-bit integers with printf

Tags:

c

printf

In Windows, it is "%I64d". In Linux and Solaris, it is "%lld".
If I want to write cross-platform printfs that prints long long values: what is good way of doing so ?

long long ll; printf(???, ll); 
like image 964
Andrei Avatar asked Jun 09 '11 20:06

Andrei


People also ask

How do I print long long int in printf?

unsigned long long int i=0;printf("\nenter num\n");scanf("%llu",&i);printf("%. 20llu\n",cp);

What is the format specifier for uint64_t?

What is the format specifier for uint64_t? for uint64_t type: #include <inttypes. h> uint64_t t; printf("%" PRIu64 "\n", t); you can also use PRIx64 to print in hexadecimal.

What is LLU C?

%lli or %lld. Long long. %llu. Unsigned long long.

What is PRIu64?

PRIu64 is a string (literal), for example the following: printf("%s\n", PRIu64); prints llu on my machine. Adjacent string literals are concatenated, from section 6.4.


2 Answers

There are a couple of approaches.

You could write your code in C99-conforming fashion, and then supply system-specific hacks when the compiler-writers let you down. (Sadly, that's rather common in C99.)

#include <stdint.h> #include <inttypes.h>  printf("My value is %10" PRId64 "\n", some_64_bit_expression); 

If one of your target systems has neglected to implement <inttypes.h> or has in some other way fiendishly slacked off because some of the type features are optional, then you just need a system-specific #define for PRId64 (or whatever) on that system.

The other approach is to pick something that's currently always implemented as 64-bits and is supported by printf, and then cast. Not perfect but it will often do:

printf("My value is %10lld\n", (long long)some_64_bit_expression); 
like image 81
DigitalRoss Avatar answered Sep 20 '22 06:09

DigitalRoss


MSVC supports long long and ll starting Visual Studio 2005.

You could check the value of the _MSC_VER macro (>= 1400 for 2005), or simply don't support older compilers.

It doesn't provide the C99 macros, so you will have to cast to long long rather than using PRId64.

This won't help if you're using older MSVC libraries with a non-MSVC compiler (I think mingw, at least, provides its own version of printf that supports ll)

like image 21
Random832 Avatar answered Sep 21 '22 06:09

Random832