void convert(int bTen) {
System.out.println("Base 10 = " + bTen);
int bTwo = 0;
int leftOver = bTen;
while (leftOver > 0) {
int i = 0;
int remains = 0;
while (remains >= 0) {
remains = leftOver - (int)Math.pow(2, i);
i++;
}
bTwo += Math.pow(10, i - 2);
leftOver = leftOver - (int)Math.pow(2, i - 2);
}
System.out.println("Base 2 = " + bTwo);
}
I was wondering why the above code can convert numbers in base-10 to base-2. I know how to write a program to convert base-2 to base-10 but I can’t seem to understand how to do the reverse.
First, I think this conversion is unreasonable and shouldn’t be done such way.
Base-10 or Base-2 is simply a textual representation of same number. However your logic is changing a number (A) to another number (B), for which if you are reading B in base-10 it will look the same as base-2 of A.
Anyway, the idea of the logic of your quoted code is something like this: