C语言 如何在C中显示十六进制数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3649026/
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
How to display hexadecimal numbers in C?
提问by codaddict
I have a list of numbers as below:
我有一个数字列表如下:
0, 16, 32, 48 ...
0, 16, 32, 48 ...
I need to output those numbers in hexadecimal as:
我需要以十六进制输出这些数字:
0000,0010,0020,0030,0040 ...
0000,0010,0020,0030,0040 ...
I have tried solution such as:
我尝试过解决方案,例如:
printf("%.4x",a); // where a is an integer
but the result that I got is:
但我得到的结果是:
0000, 0001, 0002, 0003, 0004 ...
0000, 0001, 0002, 0003, 0004 ...
I think I'm close there. Can anybody help as I'm not
so good at printfin C.
我想我就在那里。任何人都可以提供帮助,因为我printf在 C 方面不太擅长。
Thanks.
谢谢。
回答by codaddict
Try:
尝试:
printf("%04x",a);
0- Left-pads the number with zeroes (0) instead of spaces, where padding is specified.4(width) - Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is right justified within this width by padding on the left with the pad character. By default this is a blank space, but the leading zero we used specifies a zero as the pad char. The value is not truncated even if the result is larger.x- Specifier for hexadecimal integer.
0- 用零 (0) 而不是空格左填充数字,其中指定了填充。4(width) - 要打印的最小字符数。如果要打印的值比此数字短,则通过在左侧填充填充字符,结果在此宽度内右对齐。默认情况下,这是一个空格,但我们使用的前导零将零指定为填充字符。即使结果更大,该值也不会被截断。x- 十六进制整数的说明符。
More here
更多在这里
回答by zeilja
i use it like this:
我像这样使用它:
printf("my number is 0x%02X\n",number);
// output: my number is 0x4A
Just change number "2" to any number of chars You want to print ;)
只需将数字“2”更改为您想要打印的任意数量的字符;)
回答by hmofrad
You can use the following snippet code:
您可以使用以下代码段:
#include<stdio.h>
int main(int argc, char *argv[]){
unsigned int i;
printf("decimal hexadecimal\n");
for (i = 0; i <= 256; i+=16)
printf("%04d 0x%04X\n", i, i);
return 0;
}
It prints both decimal and hexadecimal numbers in 4 places with zero padding.
它以零填充在 4 位打印十进制和十六进制数字。
回答by loxxy
Your code has no problem. It does print the way you want. Alternatively, you can do this:
你的代码没有问题。它确实以您想要的方式打印。或者,您可以这样做:
printf("%04x",a);

