C++ Small char to hex function?

5.5k views Asked by At

I'm trying to find a very lightweight way to either hex a char or md5 one with two examples below.

char example[0x34];
char example_final[0x200];
sprintf(example, "%s", "4E964DCA5996E48827F62A4B7CCDF045");

For an example using two PHP functions below.

MD5:

sprintf(example_final, "%s", md5(example));
output: 149999b5b26e1fdeeb059dbe0b36c3cb

HEX:

sprintf(example_final, "%s", bin2hex(example));
output: 3445393634444341353939364534383832374636324134423743434446303435

Which ever is the most lightweight way to do it. I was thinking some big array of char to it's hex value than making a loop foreach char, but unsure.

1

There are 1 answers

2
Mats Petersson On BEST ANSWER

An example of bin2hex would look like this:

#include <string>
#include <iostream>


std::string bin2hex(const std::string& input)
{
    std::string res;
    const char hex[] = "0123456789ABCDEF";
    for(auto sc : input)
    {
        unsigned char c = static_cast<unsigned char>(sc);
        res += hex[c >> 4];
        res += hex[c & 0xf];
    }

    return res;
}


int main()
{
    std::string example = "A string";

    std::cout << "bin2hex of " << example << " gives " << bin2hex(example) << std::endl;
}