Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to printf a 64-bit integer as hex? [duplicate]

Tags:

c

gcc

64-bit

With the following code I am trying to output the value of a unit64_t variable using printf(). Compiling the code with gcc, returns the following warning:

warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 2 has type ‘uint64_t’ [-Wformat=]

The code:

#include <stdio.h> #include <stdint.h>  int main () {     uint64_t val = 0x1234567890abcdef;     printf("val = 0x%x\n", val);      return 0; } 

The output:

val = 0x90abcdef 

Expected output:

val = 0x1234567890abcdef 

How can I output a 64bit value as a hexadecimal integer using printf()? The x specifier seems to be wrong in this case.

like image 422
sergej Avatar asked Aug 20 '15 07:08

sergej


2 Answers

The warning from your compiler is telling you that your format specifier doesn't match the data type you're passing to it.

Try using %lx or %llx. For more portability, include inttypes.h and use the PRIx64 macro.

For example: printf("val = 0x%" PRIx64 "\n", val); (note that it's string concatenation)

like image 152
tangrs Avatar answered Sep 21 '22 02:09

tangrs


Edit: Use printf("val = 0x%" PRIx64 "\n", val); instead.

Try printf("val = 0x%llx\n", val);. See the printf manpage:

ll (ell-ell). A following integer conversion corresponds to a long long int or unsigned long long int argument, or a following n conversion corresponds to a pointer to a long long int argument.

Edit: Even better is what @M_Oehm wrote: There is a specific macro for that, because unit64_t is not always a unsigned long long: PRIx64 see also this stackoverflow answer

like image 35
Superlokkus Avatar answered Sep 22 '22 02:09

Superlokkus