I'm writing a simple Java program to convert from decimal to binary.
public static int toBinary(int n) {
int result = 0;
while (n >= 1) {
int power = 0;
while ((int) Math.pow(2, power) <= n) {
power++;
}
result += (int) Math.pow(10, power - 1);
n = n - (int) Math.pow(2, power - 1);
}
return result;
}
The program works for n up until 1023, but fails after that and I'm not sure where I did wrong. Can someone help?
Intsare already in binary. What you want is the binary representation of a decimal number. So just useInteger.toBinaryString(). If you grow your own, store the result in a String, not an int. Here is one example of how to do it.