C: 以十六进制打印 "unsigned long" 的正确方法
C: Correct way to print "unsigned long" in hex
我有一个函数获取一个 unsigned long 变量作为参数,我想以十六进制打印它。
正确的做法是什么?
目前,我使用 printf 和 "%lx"
void printAddress(unsigned long address) {
printf("%lx\n", address);
}
我应该寻找 unsigned 长十六进制的 printf 模式吗? (而不仅仅是上面提到的“长十六进制”)
或者 printf 仅使用位将数字转换为十六进制? - 所以我不应该关心这个标志?
Edit/Clarification
这个问题的根源在于混淆:十六进制只是另一种表达位的方式,这意味着signed/unsigned数字只是一种解释。事实上,类型是 unsigned long 因此不会改变十六进制数字。 Unsigned 只是告诉您如何在您的计算机程序中解释这些相同的位。
我认为下面的格式说明符应该可以工作
试一试
printf("%#lx\n",address);
你做得对。
o, u, x, X
The unsigned int argument is converted to unsigned octal (o), unsigned decimal (u), or unsigned hexadecimal (x and X) notation.
因此 x
的值应始终为 unsigned
。要使其大小为 long
,请使用:
l
(ell) A following integer conversion corresponds to a long int or unsigned long int argument [...]
所以 %lx
是 unsigned long
。但是,地址(指针值)应使用 %p
打印并转换为 void *
.
我有一个函数获取一个 unsigned long 变量作为参数,我想以十六进制打印它。
正确的做法是什么?
目前,我使用 printf 和 "%lx"
void printAddress(unsigned long address) {
printf("%lx\n", address);
}
我应该寻找 unsigned 长十六进制的 printf 模式吗? (而不仅仅是上面提到的“长十六进制”)
或者 printf 仅使用位将数字转换为十六进制? - 所以我不应该关心这个标志?
Edit/Clarification
这个问题的根源在于混淆:十六进制只是另一种表达位的方式,这意味着signed/unsigned数字只是一种解释。事实上,类型是 unsigned long 因此不会改变十六进制数字。 Unsigned 只是告诉您如何在您的计算机程序中解释这些相同的位。
我认为下面的格式说明符应该可以工作 试一试
printf("%#lx\n",address);
你做得对。
o, u, x, X
The unsigned int argument is converted to unsigned octal (o), unsigned decimal (u), or unsigned hexadecimal (x and X) notation.
因此 x
的值应始终为 unsigned
。要使其大小为 long
,请使用:
l
(ell) A following integer conversion corresponds to a long int or unsigned long int argument [...]
所以 %lx
是 unsigned long
。但是,地址(指针值)应使用 %p
打印并转换为 void *
.