C语言 C:以十六进制打印“unsigned long”的正确方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29509452/
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 11:50:18  来源:igfitidea点击:

C: Correct way to print "unsigned long" in hex

cprintf

提问by SomethingSomething

I have a function that gets an unsigned longvariable as parameter and I want to print it in Hex.

我有一个函数,它获取一个unsigned long变量作为参数,我想以十六进制打印它。

What is the correct way to do it?

正确的做法是什么?

Currently, I use printfwith "%lx"

目前,我将printf“%lx”一起使用

void printAddress(unsigned long address) {
    printf("%lx\n", address);
}

Should I look for a printf pattern for unsignedlong hex? (and not just "long hex" as mentioned above)

我应该为无符号长十六进制寻找 printf 模式吗?(而不仅仅是上面提到的“长十六进制”)

Or does printfconvert numbers to hex only using the bits? - so I should not care about the sign anyway?

还是printf仅使用位将数字转换为十六进制?- 所以我不应该关心这个标志吗?

回答by unwind

You're doing it right.

你做得对。

From the manual page:

手册页

o, u, x, X

The unsigned int argument is converted to unsigned octal (o), unsigned decimal (u), or unsigned hexadecimal (x and X) notation.

o, u, x, x

unsigned int 参数被转换为无符号八进制 (o)、无符号十进制 (u) 或无符号十六进制(x 和 X)表示法。

So the value for xshould always be unsigned. To make it longin size, use:

所以它的值x应该总是unsigned. 要使其long尺寸变大,请使用:

l

(ell) A following integer conversion corresponds to a long int or unsigned long int argument [...]

(ell) 以下整数转换对应于 long int 或 unsigned long int 参数 [...]

So %lxis unsigned long. An address (pointer value), however, should be printed with %pand cast to void *.

所以%lxunsigned long。但是,地址(指针值)应该打印%p并转换为void *.

回答by Himanshu Sourav

I think the following format specifier should work give it a try

我认为以下格式说明符应该可以尝试一下

printf("%#lx\n",address);

printf("%#lx\n",address);