如何打印无符号长整型int(无符号长整型int的格式说明符)?

时间:2020-03-05 18:37:52  来源:igfitidea点击:
#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);

回答

非标准的东西总是很奇怪:)

长期的
在GNU下它是Lll或者q

在Windows下,我相信它只是" ll"

回答

好吧,一种方法是使用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编译器。

回答

我们可能想尝试使用为我们提供以下类型的inttypes.h库
int32_tint64_tuint64_t等。
然后,我们可以使用其宏,例如:

uint64_t x;
uint32_t y;

printf("x: %"PRId64", y: %"PRId32"\n", x, y);

这是"保证"的,不会给我们带来longunsigned long long等麻烦,因为我们不必猜测每种数据类型有多少位。

回答

这是因为%llu在Windows下无法正常工作,并且%d无法处理64位整数。我建议改用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.

回答

在Linux中是%llu,在Windows中是%I64u

尽管我发现它在Windows 2000中不起作用,但那里似乎有一个错误!

回答

对于使用MSVS的很长一段时间(或者__int64),应该使用%I64d:

__int64 a;
time_t b;
...
fprintf(outFile,"%I64d,%I64d\n",a,b);    //I is capital i