Linux 在 C 中打印十六进制的前导零
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12062916/
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
Printing leading zeroes for hexadecimal in C
提问by Gregory-Turtle
I am trying to print the results of an MD5 hash to the console and it is working for the most part. To ensure correctness, I used an online MD5 calculator to compare results. Most of the characters are the same, but a few are missing in mine and they are are all leading zeroes.
我正在尝试将 MD5 散列的结果打印到控制台,并且它在大部分情况下都在工作。为了确保正确性,我使用了在线 MD5 计算器来比较结果。大多数字符都是相同的,但我的中缺少一些字符,它们都是前导零。
Let me explain. The result is a 16 byte unsigned char *. I print each of these bytes one by one. Each byte prints TWO characters to the screen. However, if the first character out of the two is a zero, it does not print the zero.
让我解释。结果是一个 16 字节的 unsigned char *。我一个一个地打印这些字节中的每一个。每个字节在屏幕上打印两个字符。但是,如果两个字符中的第一个字符是零,则不会打印零。
printk("%x", result);
Result is of type unsigned char*. Am I formatting it properly or am I missing something?
结果是 unsigned char* 类型。我是正确格式化还是遗漏了什么?
采纳答案by aschepler
Use "%02x"
.
使用"%02x"
.
The two means you always want the output to be two characters wide.
这两个意味着您总是希望输出为两个字符宽。
The zero means if padding is necessary, to use zeros instead of spaces.
零意味着如果需要填充,则使用零而不是空格。
回答by ouah
result
is a pointer, use a loop to print all the digits:
result
是一个指针,使用循环打印所有数字:
int i;
for (i = 0; i < 16; i++) {
printf("%02x", result[i]);
}