C语言 无符号长十六进制表示
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19478509/
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
Unsigned long hexadecimal representation
提问by Shraddha
#include <stdio.h>
#include <string.h>
int main(void) {
char buf[256] = {};
unsigned long i=13835058055298940928;
snprintf(buf, 1024, "%lx", i); /* Line 7 */
printf("%s\n",buf);
return 0;
}
In line 7, if I use %lux, and then snprintfdoesn't do any conversion. It just prints 0x13835058055298940928x, whereas if I use just %lx, it prints an expected hexadecimal conversion.
在第 7 行,如果我使用%lux, 然后snprintf不做任何转换。它只打印0x13835058055298940928x,而如果我只使用%lx,它会打印预期的十六进制转换。
How do I represent unsigned long in hexadecimal?
如何用十六进制表示 unsigned long?
回答by Keith Thompson
A format of "%lux"is treated as "%lu"(unsigned long, decimal) followed by a letter x.
的格式"%lux"被视为"%lu"(unsigned long, decimal) 后跟一个字母x。
The "%x"format requires an argument of unsigned type; there's no (direct) mechanism to print signed integers in hexadecimal format.
该"%x"格式需要一个无符号类型的参数;没有(直接)机制以十六进制格式打印有符号整数。
The format for printing an unsigned longvalue in hexadecimal is "%lx". (xis hexadecimal, dis signed decimal, uis unsigned decimal; any of them may be qualified with lfor long.)
unsigned long以十六进制打印值的格式是"%lx". (x是十六进制,d是有符号十进制,u是无符号十进制;它们中的任何一个都可以用llong限定。)
Note that the value 13835058055298940928requires at least a 64-bit unsigned type to store it without overflow. The type unsigned longis at least 32 bits; it's 64 bits on somesystems, but by no means all. If you want your code to be portable, you should use type unsigned long longrather than unsigned long. The format for printing an unsigned long longvalue in hexadecimal is "%llx".
请注意,该值13835058055298940928至少需要 64 位无符号类型才能存储而不会溢出。类型unsigned long至少为 32 位;在某些系统上它是 64 位,但绝不是全部。如果你希望你的代码是可移植的,你应该使用 typeunsigned long long而不是unsigned long. unsigned long long以十六进制打印值的格式是"%llx".
For clarity, I usually precede hexadecimal output with 0x, so it's obvious to the reader that it's a hexadecimal number:
为清楚起见,我通常在十六进制输出之前加上0x,因此读者很明显它是一个十六进制数:
printf("0x%llx\n", some_unsigned_long_long_value);
(You can achieve the same result with %#llx, but I find it easier to write out 0xthan to remember the meaning of the #flag.)
(您可以使用 获得相同的结果%#llx,但我发现写出0x比记住#标志的含义更容易。)

