C语言 格式说明符 %02x
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18438946/
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
Format specifier %02x
提问by user2717225
I have a simple program :
我有一个简单的程序:
#include <stdio.h>
int main()
{
long i = 16843009;
printf ("%02x \n" ,i);
}
I am using %02xformat specifier to get 2 char output,
However, the output I am getting is:
我正在使用%02x格式说明符来获取 2 个字符输出,但是,我得到的输出是:
1010101
while I am expecting it to be :01010101.
虽然我期待它是:01010101。
回答by aragaer
%02xmeans print at least 2 digits, prepend it with 0's if there's less. In your case it's 7 digits, so you get no extra 0in front.
%02x表示至少打印 2 位数字,0如果少则在前面加上's。在您的情况下,它是 7 位数字,因此您不会0在前面获得额外的数字。
Also, %xis for int, but you have a long. Try %08lxinstead.
另外,%x是为int,但你有一个很长的。试试吧%08lx。
回答by PulkitRajput
%xis a format specifier that format and output the hex value. If you are providing int or long value, it will convert it to hex value.
%x是格式化和输出十六进制值的格式说明符。如果您提供 int 或 long 值,它会将其转换为十六进制值。
%02xmeans if your provided value is less than two digits then 0will be prepended.
%02x意味着如果您提供的值小于两位数,0则将在前面加上。
You provided value 16843009and it has been converted to 1010101which a hex value.
您提供的值16843009已转换为1010101十六进制值。
回答by PP.
Your string is wider than your format width of 2. So there's no padding to be done.
你的字符串比你的格式宽度 2 宽。所以没有填充要做。
回答by RJM
You are actually getting the correct value out.
你实际上得到了正确的值。
The way your x86(compatible) processor stores data like this, is in Little Endianorder, meaning that, the MSB is last in your output.
您的x86(兼容)处理器存储这样的数据的方式是Little Endian顺序,这意味着 MSB 在您的输出中排在最后。
So, given your output:
因此,鉴于您的输出:
10101010
10101010
the last two hex values 10are the Most Significant Byte (2 hex digits = 1 byte = 8 bits(for (possibly unnecessary) clarification).
最后两个十六进制值10是最高有效字节(2 hex digits = 1 byte = 8 bits(用于(可能不必要的)说明)。
So, by reversingthe memory storage order of the bytes, your value is actually: 01010101.
因此,通过反转字节的内存存储顺序,您的值实际上是: 01010101。
Hope that clears it up!
希望能解决这个问题!

