Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing leading zeroes for hexadecimal in C

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?

like image 666
Gregory-Turtle Avatar asked Aug 21 '12 20:08

Gregory-Turtle


2 Answers

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.

like image 75
aschepler Avatar answered Sep 22 '22 13:09

aschepler


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

int i; for (i = 0; i < 16; i++) {    printf("%02x", result[i]); } 
like image 21
ouah Avatar answered Sep 23 '22 13:09

ouah