Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert MD5 representation to hex in C++

Tags:

c++

hex

md5

I have an MD5 string which i am converting to hex. Is there a better way to do this? I currently am doing:

unsigned char digest[16]; 
string result;
char buf[32];
for (int i=0; i<16; i++)
{
   sprintf_s(buf, "%02x", digest[i]);
   result.append( buf );
}
like image 399
John Mcdock Avatar asked May 30 '13 03:05

John Mcdock


1 Answers

This version should be faster. If you need more speed, change string result to char array.

static const char hexchars[] = "0123456789abcdef";

unsigned char digest[16];
string result;

for (int i = 0; i < 16; i++)
{
    unsigned char b = digest[i];
    char hex[3];

    hex[0] = hexchars[b >> 4];
    hex[1] = hexchars[b & 0xF];
    hex[2] = 0;

    result.append(hex);
}
like image 57
UltimaWeapon Avatar answered Sep 19 '22 04:09

UltimaWeapon