Printing leading zeroes for hexadecimal in C

CLinuxFormatting

C Problem Overview


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.

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.

printk("%x", result);

Result is of type unsigned char*. Am I formatting it properly or am I missing something?

C Solutions


Solution 1 - C

Use "%02x".

The two means you always want the output to be (at least) two characters wide.

The zero means if padding is necessary, to use zeros instead of spaces.

Solution 2 - C

result is a pointer, use a loop to print all the digits:

int i;
for (i = 0; i < 16; i++) {
   printf("%02x", result[i]);
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGregory-TurtleView Question on Stackoverflow
Solution 1 - CascheplerView Answer on Stackoverflow
Solution 2 - CouahView Answer on Stackoverflow