# Converting an inputted hex to decimal

## Recommended Posts

Sfpiano    126
Say I have an int: int i = 0x122; How can I convert it so that i = 122?

##### Share on other sites
Conner McCloud    1135
You're going to have to be a lot more specific. There's no reason to convert from 0x122 to 122, unless one or both of them is a string. Is that the case?

CM

##### Share on other sites
Overseer    162
First of all, Hex 0x122 != decimal 122, it in fact == decimal 290, and if you are trying to get a decimal value from a hex value, from a string to a integer, then personally I prefer to use lookup tables for each value [last time I did URL decoders, thats how I did it anyway] and just multiply the current value by 16 before adding the result of the next value to it. so you get something like

(((((1) * 16) + 2)* 16) + 2) = 290 = (1 * (16^2)) + (2 * (16^1)) + (2 * (16^0))
for 0x122

##### Share on other sites
Cosmic R    159
say if you did want to convert 0x122 to just 122, you could do this:

(in C)
char text[256];int num = 0x122;int newnum;sprintf(text,"%x",num);newnum = atof(text);

I think thats how you'd do it.

##### Share on other sites
Talan    122
Sounds like you want to do BCD conversion.

Just use a BCD conversion function, like so:

Decimal = (BCD >> 12) * 1000 + (BCD >> 8 & 0xf) * 100 + (BCD >> 4 & 0xf) * 10 + (BCD & 0xf);

That will work for 16-bit values, you can of course turn it into a loop for arbitrary-sized numbers. Of course, if your hex values have invalid BCD numbers in them (ie, digits A-F), then it will give you nonsense data out. GIGO! :)

Going the other way is a little more expensive, as you have to use division/modulus operations to sort out the decimal digits.

##### Share on other sites
Sfpiano    126
Quote:
 Original post by TalanSounds like you want to do BCD conversion.Just use a BCD conversion function, like so: Decimal = (BCD >> 12) * 1000 + (BCD >> 8 & 0xf) * 100 + (BCD >> 4 & 0xf) * 10 + (BCD & 0xf);That will work for 16-bit values, you can of course turn it into a loop for arbitrary-sized numbers. Of course, if your hex values have invalid BCD numbers in them (ie, digits A-F), then it will give you nonsense data out. GIGO! :)Going the other way is a little more expensive, as you have to use division/modulus operations to sort out the decimal digits.

Thanks, that's what I was looking for.

##### Share on other sites
Cosmic R    159
just wondering whats the most practical use for BCD's in game programming?