Sign in to follow this  
Sfpiano

Converting an inputted hex to decimal

Recommended Posts

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 this post


Link to post
Share on other sites
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 this post


Link to post
Share on other sites
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 this post


Link to post
Share on other sites
Quote:
Original post by Talan
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.


Thanks, that's what I was looking for.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this