Copy hex values with sprintf in C
From the code below I am trying to get the result of the result var into a string var but no success so far. What's wrong? Why I can't get the right result? If I print this directly it's ok...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/md5.h>
char *string = "stelios";
unsigned char s[MD5_DIGEST_LENGTH];
int main()
{
int i;
unsigned char result[MD5_DIGEST_LENGTH];
MD5(string, strlen(string), result);
// output
for(i = 0; i < MD5_DIGEST_LENGTH; i++){
sprintf(s,"%0x", result[i]);//
printf("%x",s[i]);
}
开发者_如何学JAVA printf("\n%x",s);
return EXIT_SUCCESS;
}
Try this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/md5.h>
char *string = "stelios";
char s[MD5_DIGEST_LENGTH * 2 + 1] = "";
int main()
{
int i;
unsigned char result[MD5_DIGEST_LENGTH];
MD5(string, strlen(string), result);
// output
for(i = 0; i < MD5_DIGEST_LENGTH; i++){
char temp[3];
sprintf(temp, "%02x", result[i]);
strcat(s, temp);
}
printf("Final Hex String: %s",s);
return EXIT_SUCCESS;
}
Each time sprintf
is called, it writes the formatted value to the beginning of s
, overwriting whatever was written there in the previous call. You need to do something like sprintf(s + i*2, "%02x", result[i]);
(and change the length of s
to 2*MD5_DIGEST_LENGTH+1
).
Here's what I've used:
char *digit="0123456789abcdef";
char hex[2*MD5_DIGEST_LENGTH+1],*h;
int i;
for (h=hex,i=0; i<N; i++)
{
*h++=digit[digest[i] >> 4];
*h++=digit[digest[i] & 0x0F];
}
*h='\0';
精彩评论