Click here to Skip to main content
15,889,651 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello!
I am making an MD5 application to hash the passwords in my database.
I successfully hashed the passwords into a Pwd_hash column in my table and it is of datatype char(32).
However, I have seen in some forums that it is best to keep the hash value in a binary(16) column.
Now, my problem is how do I convert the hex string to a binary value?

As a little example:
C++
#include <iostream>
#include <string>
#include <bitset>
using namespace std;


int main()
{
	for(short int c = 0x1; c <= 0x3; c++)
	{
        bitset<((sizeof(short int) / 2 ) * 8)/2> binary(c); //sizeof() returns bytes, not bits!
        //cout << "Letter: " << c << "\t";
        cout << "Hex: " << hex << c << "\t";
        cout << "Binary: " << binary << endl;	
    }
	return 0;
}


</bitset></string></iostream>


However, the binary value returned is a 4-byte value, where each element takes up 1 byte.
What I want is for each pair of characters in the hex string, it is converted to the corresponding binary value.
e.g 0x82 will become binary(1000 0010) and not "1000 0010". The latter would imply 8 bytes and not 1 byte.
I hope I am making myself clear...
Posted

1 solution

You have to convert two hexadecimal characters at time, e.g.
C++
string s = "ed07";
vector <unsigned char> binary;
for (string::size_type i=0; i<s.length(); i+=2)
{
  unsigned char b = (unsigned char) strtoul(s.substr(i,2).c_str(), NULL, 16);
  binary.push_back(b);
}
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900