Jump to content

Understanding base 10 -> base 2 conversion


Septron

Recommended Posts

BASE 2  [ 0, 1]
BASE 10 [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

To convert BASE 10 into BASE 2 is a simple matter.

For this example, I will choose 45 for the number.

To find the BASE 2 number of 45 you have to find the lowest

power of 2 that 45 can fit into...

 

Power of 2 ^ 0 = 1.0
Power of 2 ^ 1 = 2.0
Power of 2 ^ 2 = 4.0
Power of 2 ^ 3 = 8.0
Power of 2 ^ 4 = 16.0
Power of 2 ^ 5 = 32.0
Power of 2 ^ 6 = 64.0 <-- BINGO

So now we take it back a step to 2 ^ 5 at 32 and we have a 1

Next we repeat the process with 45 - 32 = 13

 

Power of 2 ^ 0 = 1.0
Power of 2 ^ 1 = 2.0
Power of 2 ^ 2 = 4.0
Power of 2 ^ 3 = 8.0 <-- BINGO

However, because we skiped 2 ^ 4 we need to add a 0 and a 1

We now have 101

So now we take 13 - 8 = 5

Power of 2 ^ 0 = 1.0
Power of 2 ^ 1 = 2.0
Power of 2 ^ 2 = 4.0 <-- BINGO

We now have 1011

5 - 4 = 1

Power of 2 ^ 0 = 1.0 <-- BINGO

We skipped 2 ^ 1 so we add a 0 and a 1

We now have 101101

System.out.println(Integer.parseInt("" + 101101, 2)); // = 45

Now, this could be automated using this sniplet of code found on google:

 

public static long toBinary(int n) {
        String b = ""; // binary representation as a string
        while (n != 0) {
            int r = (int) (n % 2); // remainder
            b = r + b; // concatenate remainder
            n /= 2; // reduce n
        }
        return Long.parseLong(b);
}

Now, for some people that don't understand what this is doing, let's break it down into the steps it follows in the loop

 

So to break it down the first line is actually saying, what's the remainder of n when divided by 2 and set that to r

The next line is saying add r to b (string of numbers) then set that to the current b

Finally the last line is saying divide n by 2 then set that to n

Edited by Septron
Link to comment
Share on other sites

Guest
This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...