C语言 如何将 64 位整数打印为十六进制?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32112497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 12:04:26  来源:igfitidea点击:

How to printf a 64-bit integer as hex?

cgcc64-bit

提问by sergej

With the following code I am trying to output the value of a unit64_tvariable using printf(). Compiling the code with gcc, returns the following warning:

使用以下代码,我尝试unit64_t使用printf(). 使用 gcc 编译代码,返回以下警告:

warning: format ‘%x' expects argument of type ‘unsigned int', but argument 2 has type ‘uint64_t' [-Wformat=]

警告:格式 '%x' 需要类型为 'unsigned int' 的参数,但参数 2 的类型为 'uint64_t' [-Wformat=]

The code:

编码:

#include <stdio.h>
#include <stdint.h>

int main ()
{
    uint64_t val = 0x1234567890abcdef;
    printf("val = 0x%x\n", val);

    return 0;
}

The output:

输出:

val = 0x90abcdef

Expected output:

预期输出:

val = 0x1234567890abcdef

How can I output a 64bit value as a hexadecimal integer using printf()? The xspecifier seems to be wrong in this case.

如何使用 将 64 位值输出为十六进制整数printf()x在这种情况下,说明符似乎是错误的。

回答by tangrs

The warning from your compiler is telling you that your format specifier doesn't match the data type you're passing to it.

编译器的警告告诉您格式说明符与传递给它的数据类型不匹配。

Try using %lxor %llx. For more portability, include inttypes.hand use the PRIx64macro.

尝试使用%lx%llx。为了获得更多的可移植性,请包含inttypes.h并使用PRIx64宏。

For example: printf("val = 0x%" PRIx64 "\n", val);(note that it's string concatenation)

例如:(printf("val = 0x%" PRIx64 "\n", val);注意它是字符串连接)

回答by Superlokkus

Edit: Use printf("val = 0x%" PRIx64 "\n", val);instead.

编辑:改为使用printf("val = 0x%" PRIx64 "\n", val);

Try printf("val = 0x%llx\n", val);. See the printf manpage:

试试printf("val = 0x%llx\n", val);。请参阅printf 联机帮助页

ll (ell-ell). A following integer conversion corresponds to a long long int or unsigned long long int argument, or a following n conversion corresponds to a pointer to a long long int argument.

我(嗯)。后面的整数转换对应于 long long int 或 unsigned long long int 参数,或者后面的 n 转换对应于指向 long long int 参数的指针。

Edit: Even better is what @M_Oehm wrote: There is a specific macro for that, because unit64_tis not always a unsigned long long: PRIx64see also this stackoverflow answer

编辑:更好的是@M_Oehm 写道:有一个特定的宏,因为unit64_t并不总是一个unsigned long longPRIx64另见这个stackoverflow answer