Hex to Decimal Conversion


In need of a hex to decimal conversion function the other day, I looked around on the internet but found nothing really suitable. Yes I’m using the Crypto++ libraries, but for this process I didn’t want to bring in those libs just for a hex to decimal conversion.

Yes I could use Win32 sscanf et al, but that that isn’t deterministic, and anyway it feels hacky somehow. So I wrote my own, and in the spirit of sharing here it is, and ignoring my exception invocation depends only on the CRT.

template<typename Init>
inline long std_HexToDecimal(Init itinbegin,Init itinend)
{

 int chPos = 0;
 long lResult = 0;
 –itinend;
 while(itinend >= itinbegin)
 {
  char chHex = *itinend;
  int nval = ((‘0′ <=chHex) && (chHex<=’9’))?chHex-‘0’:
             ((‘A’ <=chHex) && (chHex<=’F’))?chHex-‘A’+0x0A:
             ((‘a’ <=chHex) && (chHex<=’f’))?chHex-‘a’+0x0A:
             -1;
  if(nval == -1)
   throw MSTD_EXCEPTION0(_T(“invalid hex character”));
  lResult += (nval * (1 << (chPos*4)));
  
  chPos++;
  –itinend;
 }

 return lResult;
}

In summary a hex to decimal conversion is quite simple, starting at the last hex digit (representing a nibble) verify that its a hex digit and convert it to it’s absolute hex value, (‘0’ := 0x0, ‘A’ := 0x0A etc).

Multiply this value by 16^{digit pos}, raising 16 ^ digit pos is equivilent to left shifting 1 by digit pos * 4, 4 bits being a nibble. Digit pos 0 is the least significant hex digit.

Add this value to a sum

Proceed in this fashion from least to most significant digit

Published by

Phil Harding

SharePoint Consultant, Developer, Father, Husband and Climber.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.