#include <stdio.h>
int main() {
unsigned long long int num = 285212672; //FYI: fits in 29 bits
int normalInt = 5;
printf("My number is %d bytes wide and its value is %ul. A normal number is %d.\n", sizeof(num), num, normalInt);
return 0;
}
Output:
My number is 8 bytes wide and its value is 285212672l. A normal number is 0.
I assume this unexpected result is from printing the unsigned long long int
. How do you printf()
an unsigned long long int
?
Use the ll (el-el) long-long modifier with the u (unsigned) conversion. (Works in windows, GNU).
You may want to try using the inttypes.h library that gives you types such as
int32_t
,int64_t
,uint64_t
etc. You can then use its macros such as:This is "guaranteed" to not give you the same trouble as
long
,unsigned long long
etc, since you don't have to guess how many bits are in each data type.%d
--> forint
%u
--> forunsigned int
%ld
--> forlong int
%lu
--> forunsigned long int
%lld
--> forlong long int
%llu
--> forunsigned long long int
For long long (or __int64) using MSVS, you should use %I64d:
That is because %llu doesn't work properly under Windows and %d can't handle 64 bit integers. I suggest using PRIu64 instead and you'll find it's portable to Linux as well.
Try this instead:
Output
In Linux it is
%llu
and in Windows it is%I64u
Although I have found it doesn't work in Windows 2000, there seems to be a bug there!
Compile it as x64 with VS2005:
Non-standard things are always strange :)
for the long long portion under GNU it's
L
,ll
orq
and under windows I believe it's
ll
onlyHex:
Output:
In addition to what people wrote years ago:
main.c:30:3: warning: unknown conversion type character 'l' in format [-Wformat=]
printf("%llu\n", k);
Then your version of mingw does not default to c99. Add this compiler flag:
-std=c99
.Well, one way is to compile it as x64 with VS2008
This runs as you would expect:
For 32 bit code, we need to use the correct __int64 format specifier %I64u. So it becomes.
This code works for both 32 and 64 bit VS compiler.
Apparently no one has come up with a multi-platform* solution for over a decade since [the] year 2008, so I shall append mine ?. Plz upvote. (Joking. I don’t care.)
Solution:
lltoa()
How to use:
OP’s example:
Unlike the
%lld
print format string, this one works for me under 32-bit GCC on Windows.*) Well, almost multi-platform. In MSVC, you apparently need
_ui64toa()
instead oflltoa()
.