Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Hex String to Decimal Conversion

Status
Not open for further replies.

paul51

Programmer
May 19, 2000
38
US
I have a Hex value in a string that I need to convert to decimal. Does anyone know how to do this?
 
Try strtol or strtoul

The first parameter is the string to be converted.
The second is a pointer to a char*. It points to the character after the last character converted. If you're not using it then just put in a dummy variable.
The third parameter is the base, which, in your case, will be 16.
 
or if you want to do it by hand, the alogorithm is very simple! (sounds like homework so you might not be able to use predefined functions :p)

have some sort of enumeration that holds teh value (dec) of each hex char (0-F)...

loop through starting at the right of the string

int a;
int total=0
int j=0
int i=strlen hex
while i>0
a=get value of char at i from enum
total=total+(16^j * a)
i--; j++;


i'm assuming unsigned here.
 
Just to clarify, in drewdaman's pseudo code, "16^j" means "16 to the power of j" not "16 xor j"

^ means "exclusive or" in C/C++
^ means pointer in Pascal
^ means "to the power of" in some languages (the last one I used that had this notation was Algol 68!)

 
yeah "^" means to the power! you will have to use the pow function from the math library. what i posted was just an algorithm... with some short hand!
 
Oh, never use pow() function in that case! Better use a simple shift (<<4 for accumulated result).
get value of char at i from enum - sound mysterious and ambiguous...
 
ps. as for the enumeration... i don't really remember the syntax for it.. but if you have an enum

hexdigits={0,1,2,3,4,5,6,7,8,9,10,A,B,C,D,E,F}

there must be a way to figure out the position a certain character is at in the enumeration...

i know you can do:
days={sun, mon, tues, .., etc}
and sun=1, mon=2 etc.
maybe the reverse is possible? i haven't used enums in a long time.. so i can't remember... but the point was that you should map the hex digit to a decimal digit some how. the enum was just a suggestion...
 
The pow() function is too expensive: floating point calculations with exp and log (). We have integral type data and powers of 16 in the case above.
So using pow() == nuclear strike against a petty thief.
 
Polu - how old? Make a guess. Cut my teeth on Algol 60 on an ICL 1904S in 1975.
 
a homebrew fragile algorithm that half-works is simple (obviously! haha) but the CORRECT algorithm that works across character sets is in the library functions strtol() and strtoul().
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top