Click to See Complete Forum and Search --> : Alphanumeric division (base 10 to base 16)


scarleton
March 7th, 2003, 05:31 PM
Folks,

Alphanumeric division

Folks,

I have a dilemma. I have an alphanumeric number that is 24 digits long, which is base ten. I need to convert it to base 16. I know that I can divide the whole number by 16 to get the first digit, and then divided the answer again to get the next digit.

Example:

Start with 513 (we all know that 201h)

513/16 = 32 R1
32/16 = 2 R0
2/16 = 0 R2

Unroll it and you have the 201. Now I know that it is possible to do long division on a alphanumeric number, but I was wondering if there way any preexisting code samples to do alphanumeric division. Or is there a better way to achieve what I am trying to do?

Sam
http://www.miltonstreet.com/images/nb-thumbnail.jpg (http://www.miltonstreet.com/~carleton/cars/tdi-newbeetle.html)

mwilliamson
March 7th, 2003, 05:49 PM
std::ostringstream ss;
long n = 513;
ss << hex << n;
ss.str(); // = hex version of n ( 0x0201 )

If you have some desire to convert it yourself you should know that the digits of hex are:

1 | 16 | 256 | 4096 ...

So. To get the 4096 in this case, we should int divide by 4096 and process the remainder:

513 / 4096 = 0
513 % 4096 = 513.

Then we go on to 256:

513 / 256 = 2
513 % 256 = 1

Then 16:

1 / 16 = 0
1 % 16 = 1

Then 1:

1 / 1 = 1
1 % 1 = 0 // should end up with 0 if your algrithm works

So basically you use need a reverse loop starting at how over many digits will be in your hex string ( exp( 16, strlen-1 ) ).

scarleton
March 7th, 2003, 06:01 PM
a couple problems here. First of the number that I have is this:

char number[25];
strcpy(number, "123546789123456789123456");

This I need to get to hex:

7C1FB0D758001180h

I used the calculator that come with windows to do the conversion, but I don't think that will work programmtically :D

std::stringstream will not work because the number is a string. (I believe that I was mistaken in saying alphanumeric.)

And finally:

F1h (0xF1) is 241 base 10.
FFh is 255, so --> 100h is 256.
100h + 100h = 200h, and 256 + 256 = 512, so --> 200h = 512.
200h + 1h = 201h, 512 + 1 = 513, so --> 201h = 513

If you still doubt me, play with the Windows calculator in Scientific mode.