如何使用printf格式化unsigned long long int?
#include 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; }
输出:
My number is 8 bytes wide and its value is 285212672l. A normal number is 0.
我假设这个意外的结果来自打印unsigned long long int
。 你如何printf()
一个unsigned long long int
?
将ll(el-el)long-long修饰符与u(无符号)转换一起使用。 (适用于Windows,GNU)。
printf("%llu", 285212672);
您可能想尝试使用inttypes.h库,它为您提供类型,如int32_t
, int64_t
, uint64_t
等。然后您可以使用其宏,例如:
uint64_t x; uint32_t y; printf("x: %"PRId64", y: %"PRId32"\n", x, y);
由于您不必猜测每种数据类型中有多少位,因此“保证”不会给您带来与long
, unsigned long long
等相同的麻烦。
%d
– >表示int
%u
– >表示unsigned int
%ld
– > for long int
%lu
– >表示unsigned long int
%lld
– > for long long int
%llu
– >表示unsigned long long int
对于使用MSVS的long long(或__int64),您应该使用%I64d:
__int64 a; time_t b; ... fprintf(outFile,"%I64d,%I64d\n",a,b); //I is capital i
这是因为%llu在Windows下无法正常工作,%d无法处理64位整数。 我建议改用PRIu64,你会发现它也可以移植到Linux上。
试试这个:
#include #include int main() { unsigned long long int num = 285212672; //FYI: fits in 29 bits int normalInt = 5; /* NOTE: PRIu64 is a preprocessor macro and thus should go outside the quoted string. */ printf("My number is %d bytes wide and its value is %" PRIu64 ". A normal number is %d.\n", sizeof(num), num, normalInt); return 0; }
产量
My number is 8 bytes wide and its value is 285212672. A normal number is 5.
在Linux中它是%llu
,在Windows中它是%I64u
虽然我发现它在Windows 2000中不起作用,但似乎有一个错误!
使用VS2005将其编译为x64:
%llu效果很好。
非标准的东西总是很奇怪:)
对于GNU下的长长的部分,它是L
, ll
或q
在Windows下,我相信它只会
hex:
printf("64bit: %llp", 0xffffffffffffffff);
输出:
64bit: FFFFFFFFFFFFFFFF
除了几年前人们写的东西:
- 你可能会在gcc / mingw上遇到这个错误:
main.c:30:3: warning: unknown conversion type character 'l' in format [-Wformat=]
printf("%llu\n", k);
然后您的mingw版本不会默认为c99。 添加此编译器标志: -std=c99
。
好吧,一种方法是使用VS2008将其编译为x64
这可以按照您的预期运行:
int normalInt = 5; unsigned long long int num=285212672; printf( "My number is %d bytes wide and its value is %ul. A normal number is %d \n", sizeof(num), num, normalInt);
对于32位代码,我们需要使用正确的__int64格式说明符%I64u。 所以它变成了。
int normalInt = 5; unsigned __int64 num=285212672; printf( "My number is %d bytes wide and its value is %I64u. A normal number is %d", sizeof(num), num, normalInt);
此代码适用于32位和64位VS编译器。