你如何printf一个unsigned long long int(unsigned long long int的格式说明符)?

wfuga 发布于 2018-02-25 c 最后更新 2018-02-25 01:07 676 浏览

#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 intprintf() unsigned long long int如何?
已邀请:

aet

赞同来自:

使用ll(el-el)long-long修饰符和u(无符号)转换。 (在Windows,GNU中工作)。

printf("%llu", 285212672);

yeum

赞同来自:

非标准的东西总是很奇怪:) 很长一段时间 在GNU下它是Lllq 并在Windows下,我相信它只是ll

cnon

赞同来自:

那么,一种方法是用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编译器。

tin

赞同来自:

你可能想尝试使用给你类型的inttypes.h库 int32_tint64_tuint64_t等。 然后你可以使用它的宏,例如:

uint64_t x;
uint32_t y;
printf("x: %"PRId64", y: %"PRId32"\n", x, y);
这是“保证”不会给你像longunsigned long long等相同的麻烦,因为你不必猜测每种数据类型有多少位。

edolor

赞同来自:

这是因为%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.

nipsa

赞同来自:

在Linux中是%llu,在Windows中是%I64u 虽然我发现它在Windows 2000中不起作用,但似乎有一个错误!

funde

赞同来自:

对于使用MSVS很长时间(或__int64),您应该使用%I64d:

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

xporro

赞同来自:

使用VS2005将其编译为x64:

%llu works well.

uqui

赞同来自:

%d - > int %ld - > long int %lld - > long long int %llu - > unsigned long long int

mqui

赞同来自:

十六进制:

printf("64bit: %llp", 0xffffffffffffffff);
输出:
64bit: FFFFFFFFFFFFFFFF

gautem

赞同来自:

除了几年前人们写的东西:

  • 你可能在gcc/mingw上得到这个错误:
  • main.c:30:3: warning: unknown conversion type character 'l' in format [-Wformat=] printf("%llu\n", k); 那么你的mingw版本不会默认为c99。添加这个编译器标志:-std=c99