I have a program whose intention is to take in a decimal integer and return the binary value.
public static int returnBinary(int number) {
int current;
int digit = 1;
int result = 0;
while (number > 0) {
current = number % 2;
number = number/2;
result = result + current * digit;
digit = digit * 10;
}
return result;
}
This program works perfectly until it reaches the value 1024, for which it returns the value: 1410065408
Larger values than 1024 also do not work. I noticed 1023 in binary is 1111111111, which may be relevant as to why 1024 does not work.
resultis a decimalintbut containing only0and1? Maximum value forintis about 2.1 billion - you're likely exceeding that. Anything wrong withInteger.toBinaryString.