Reputation: 9451
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?
Upvotes: 13
Views: 59232
Reputation: 11
longint = 0x1BCDEFABCDEFCDEF; /* 2003520930423229935 */ you can print as-
printf("%llx", longint);
Upvotes: 1
Reputation: 9466
This is OS dependent. If you're doing this on just about any GCC that uses GLIBC, then %llx works.
However if you are using mingw compiler, then this uses Microsoft libraries, and you need to look into their documentation.
This changes your program to:
longint = 0x1BCDEFABCDEFCDEFLL; /* 2003520930423229935 */
printf("Sizeof: %d-bit\n", sizeof(longint) * 8); /* Correct */
printf("%I64x\n", longint); /* Incorrect */
printf("%x%x\n", *(((int*)(&longint))+1), longint); /* Correct */
printf("%I64d\n", longint);
Upvotes: 6
Reputation: 9451
Finally got it:
longint = 0x1BCDEFABCDEFCDEF; /* 2003520930423229935 */
printf("%I64d\n", longint);
printf("%I64x\n", longint);
Prints:
2003520930423229935
1bcdefabcdefcdef
Thanks @npclaudiu!
Upvotes: 0
Reputation: 180867
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.
Upvotes: 11
Reputation: 28525
See if %I64d
helps you. %lld
is fine for long long int
but things get really different sometimes on Windows IDEs
Upvotes: 11