你如何printf一个无符号的long long int(unsigned long long int的格式说明符)?
#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; }
输出:
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
等types。然后可以使用它的macros,例如:
uint64_t x; uint32_t y; printf("x: %"PRId64", y: %"PRId32"\n", x, y);
这是“保证”,不会给你long
, unsigned long long
等相同的麻烦,因为你不必猜测每个数据types有多less位。
很长一段时间(或__int64)使用MSVS,你应该使用%I64d:
__int64 a; time_t b; ... fprintf(outFile,"%I64d,%I64d\n",a,b); //I is capital i
这是因为%llu在Windows下无法正常工作,%d无法处理64位整数。 我build议使用PRIu64,而且你会发现它也可以移植到Linux上。
试试这个:
#include <stdio.h> #include <inttypes.h> 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.
%d
– >为int
%ld
– > long int
%lld
– > long long int
%llu
– >为unsigned long long int
用VS2005编译为x64:
%llu工作得很好。
在Linux中是%llu
,在Windows中是%I64u
虽然我发现它在Windows 2000中不起作用,但似乎有一个错误!
非标准的东西总是很奇怪:)
在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编译器。