c - 如何在 C 中可移植地打印 int64_t 类型

标签 c stdint

C99 标准具有字节大小的整数类型,如 int64_t。我目前正在使用 Windows 的 %I64d 格式(或未签名的 %I64u),例如:

#include <stdio.h>
#include <stdint.h>
int64_t my_int = 999999999999999999;
printf("This is my_int: %I64d\n", my_int);

我得到了这个编译器警告:

warning: format ‘%I64d’ expects type ‘int’, but argument 2 has type ‘int64_t’

我试过:

printf("This is my_int: %lld\n", my_int); // long long decimal

但我收到了同样的警告。我正在使用这个编译器:

~/dev/c$ cc -v
Using built-in specs.
Target: i686-apple-darwin10
Configured with: /var/tmp/gcc/gcc-5664~89/src/configure --disable-checking --enable-werror --prefix=/usr --mandir=/share/man --enable-languages=c,objc,c++,obj-c++ --program-transform-name=/^[cg][^.-]*$/s/$/-4.2/ --with-slibdir=/usr/lib --build=i686-apple-darwin10 --program-prefix=i686-apple-darwin10- --host=x86_64-apple-darwin10 --target=i686-apple-darwin10 --with-gxx-include-dir=/include/c++/4.2.1
Thread model: posix
gcc version 4.2.1 (Apple Inc. build 5664)

我应该使用哪种格式在没有警告的情况下打印 my_int 变量?

最佳答案

对于 int64_t 类型:

#include <inttypes.h>
int64_t t;
printf("%" PRId64 "\n", t);

对于 uint64_t 类型:

#include <inttypes.h>
uint64_t t;
printf("%" PRIu64 "\n", t);

您还可以使用 PRIx64 以十六进制打印。

cppreference.com has a full listing所有类型的可用宏,包括 intptr_t (PRIxPTR)。 scanf 有单独的宏,例如 SCNd64


PRIu16 的典型定义是“hu”,因此隐式字符串常量连接发生在编译时。

为了让您的代码完全可移植,您必须使用 PRId32 等来打印 int32_t"%d" 或类似的用于打印 int

关于c - 如何在 C 中可移植地打印 int64_t 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9225567/

相关文章:

c - 你如何确定你的机器是否支持 C 中的标准整数数据类型?

c - 当我将指针初始化为NULL时,运行结果很奇怪

c++ - 静态与新建/Malloc

c - int_least16_t 是否有可能成为 int 而不是 short 的别名?

c - 如何从 int32_t 中提取字节 block 并使用 c 将其存储在 int16_t 或 int8_t 中?

c++ - 如何检查是否定义了固定宽度整数

c++ - 应用编译器选项 -00 与 -03 在 clang 上调用 malloc 的不同输出

c - 如何用关键操作替换ClutterTexture?

c - 函数参数中的 int * 与 int [] 与 int (*)[] 。我应该使用哪一个?

c - 如何在 C 中移植打印 int64_t 类型