Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print 64-bit integer in GCC 4.4.1?

Tags:

c

gcc

codeblocks

I am using Code::Blocks with GCC 4.4.1 and I seem to be unable to print 64-bit signed integers from my C-code.

This code:

long long longint;

longint = 0x1BCDEFABCDEFCDEF; /* 2003520930423229935 */
printf("Sizeof: %d-bit\n", sizeof(longint) * 8);     /* Correct */
printf("%llx\n", longint);                           /* Incorrect */
printf("%x%x\n", *(((int*)(&longint))+1), longint);  /* Correct */
printf("%lld\n", longint);                           /* Incorrect */ 

Produces output:

Sizeof: 64-bit
cdefcdef
1bcdefabcdefcdef
-839922193

64-bit arithmetic seems to work correctly:

longint -= 0x1000000000000000;
printf("%x%x\n", *(((int*)(&longint))+1), longint);

Gives:

bcdefabcdefcdef

Am I missing something?

like image 984
Fenikso Avatar asked Apr 19 '12 06:04

Fenikso


People also ask

How can I use 64-bit integer?

64-bit unsigned integer type is used to store only pozitiv whole number. 64-bit unsigned integer and his value range: from 0 to 18446744073709551615.

How do I print a 64-bit integer in hex?

basically, use the PRIx64 macro from <inttypes. h> . Use printf("val = %#018"PRIx64"\n", val); to print leading zeros. Don't forget to #include <inttypes.

How do I declare a 64-bit integer in C++?

Microsoft C/C++ features support for sized integer types. You can declare 8-, 16-, 32-, or 64-bit integer variables by using the __intN type specifier, where N is 8, 16, 32, or 64.

What is the 64-bit integer type?

A 64-bit signed integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). A 64-bit unsigned integer. It has a minimum value of 0 and a maximum value of (2^64)-1 (inclusive).


2 Answers

To (in C99 and up) portably print 64 bit integers, you should #include <inttypes.h> and use the C99 macros PRIx64 and PRId64. That would make your code;

printf("Sizeof: %d-bit\n", sizeof(longint) * 8);
printf("%" PRIx64 "\n", longint);
printf("%" PRId64 "\n", longint);

Edit: See this question for more examples.

like image 174
Joachim Isaksson Avatar answered Oct 14 '22 13:10

Joachim Isaksson


longint = 0x1BCDEFABCDEFCDEF; /* 2003520930423229935 */ you can print as-

printf("%llx", longint);

like image 40
Amit Rai Avatar answered Oct 14 '22 12:10

Amit Rai