PDA

View Full Version : change the numberbase

neafriem
18-07-2004, 09:23 AM
I'm not really sure that that is the word to use, numberbase but I'm not a english speaking person so I have to guess. I want to have a program that change a number that has the numberbase 2 to a number that have the base 256. How do you do that. If it's too difficult, where can I find a program thats is ready for download?

Harry Hunt
18-07-2004, 10:29 AM
You basically want to concert a binary number to a number to the base of 256? That means each "digit" of your number would range from 0 to 255.

Well, here's one way of doing it (probably not the most effective):
Covert your binary number to decimal. This is very easy.
If for example you have the number

11010101110101110
Then this equals
(0 * 2^0) + (1 * 2^1) + (1 * 2^2)...

Now you should have a decimal number like 109486

To convert your number to the base of 256, you can now do this:

109486 mod 256 = 174
109486 div 256 = 427
427 mod 256 = 171
427 div 256 = 1
1 mod 256 = 1

So 109486 to the base 256 is
1_171_174

If you can't figure it out, i can hook you up with some code. But you should try it yourself first. It's not too hard.

neafriem
18-07-2004, 10:47 AM
thanks, I got it working. But how do I it the other way? from the base 256 to binary?

Harry Hunt
18-07-2004, 11:41 AM
Here's how:

You have 1_171_174

That is (174 * 256^0) + (171 * 256^1) + (1 * 256^2) = 109486
in decimal

To convert it to binary you do this

109486 mod 2 = 0
109486 div 2 = 54743
54743 mod 2 = 1
54743 div 2 = 27371
...

--> 11010101110101110

This is identical to my last post with the exception that you now divide/modulo by 2 and not by 256.

Harry Hunt
18-07-2004, 11:48 AM
Here's a cool trick to do the whole thing faster

Let's say you have this binary number
11010101110101110

and want to convert it to the base of 256
Now a base of 256 means each digit can range from 0 to 255. 255 in binary is 11111111 which has eight digits.

Now divide your original number into blocks of eight starting from the end
1 10101011 10101110

Now let's look at each block individually

10101110 = (0 * 2^0) + (1 * 2^1)... = 174
10101011 = ... = 171
1 = 1

---> 1_171_174

This is how you can go from binary to the base of 256 without converting to decimal first.

This also works the other way round
1_171_174 in binary
1_10101011_10101110 = 11010101110101110