Thursday, July 9, 2009

Hex Converters by C++

// Copied from http://www.dreamincode.net/code/snippet805.htm
// Another variation on hex converters with example code.
// Converts hex strings to long number and vice versa.
// (DecimalToHex() based on snipptet by Xing 2006-12-03 )


#include
#include

using namespace std;

//
// return a decimal value of hex character in the range 0 to 15.
//
unsigned char bHexToDecimal(char ch)
{
if(ch >= '0' && ch <= '9') return ch -48;
if(ch >= 'A' && ch <= 'F') return ch -55;
if(ch >= 'a' && ch <= 'f') return ch -87;
return 0;
}
//
// return a decimal long from a hexadecimal string.
// string may be preceeded with 0x or 0X
//
long HexToDecimal(string strHex)
{
unsigned long num = 0,
bit_shift = 0;

size_t len = strHex.length();
char * chAr = (char*)strHex.data();

while(len--)
{
if(chAr[len] == 'x' || chAr[len] == 'X') break;
num += ((bHexToDecimal(chAr[len])) << bit_shift);
bit_shift += 4;
}

return num;
}

//
// DecimalToHex
// Convert decimal number to a hex string in the format 0x00000000
//
string DecimalToHex(unsigned long num)
{
string strHex = "0x00000000"; //default format
char * lpCh = (char*)strHex.data() + strHex.length() -1;//seekend

while(num)
{ *lpCh-- = "0123456789ABCDEF"[num&15];
num >>= 4;
}
return strHex;
}
//
// example
//
void main()
{

string strHexNumber = "bc";
cout << "Decimal value of hex: " << strHexNumber << " is : " <<
HexToDecimal(strHexNumber) << endl;

strHexNumber = "0xFFFFFFFF";
cout << "Decimal value of hex: " << strHexNumber << " is : " <<
HexToDecimal(strHexNumber) << endl;

cout << "188 in hex is: " << DecimalToHex(188) << endl;
cout << "-1 in hex is: " << DecimalToHex(-1) << endl;

system("pause");

}//

No comments: