Reputation: 1399
I would like to convert my MD5 hash to 4 hex numbers. What's wrong in my code?
//hash = 8ce4b16b22b58894aa86c421e8759df3
char *hash = argv[1];
unsigned int parts[4];
sscanf(&hash[0], "%x", &parts[0]);
sscanf(&hash[8], "%x", &parts[1]);
sscanf(&hash[16], "%x", &parts[2]);
sscanf(&hash[24], "%x", &parts[3]);
printf("Part[0]: %x\n", parts[0]);
printf("Part[1]: %x\n", parts[1]);
printf("Part[2]: %x\n", parts[2]);
printf("Part[3]: %x\n", parts[3]);
Upvotes: 0
Views: 557
Reputation: 21
In your code, you are trying to tell sscanf() where to start parsing the string (stored in the variable named "hash"), but you aren't telling sscanf() where it should stop parsing it. Try inserting whitespace characters into "hash" where you want the 4 numbers to be divided, first, and then your code may work. Also, I would write "&(hash[0])" instead of "&hash[0]" because I don't want to clutter my memory banks with trivia such as the operator precedence rules for C - easier just to use parentheses to force what I want.
Upvotes: 1
Reputation: 134356
In your code, you wanted but forgot to limit the input for the HEX value to 8 (in characters). You need to use the field width specifier with the format specifier. You will need something like
sscanf(&hash[0], "%8x", &parts[0]);
sscanf(&hash[8], "%8x", &parts[1]);
sscanf(&hash[16], "%8x", &parts[2]);
sscanf(&hash[24], "%8x", &parts[3]);
Upvotes: 1