I made a simple Java BlueJ program converting binary to decimal using recursive technique, which the question asks me to do. It's working fine for most values but there is a problem with 011.
When I input 11
it returns 3
. but when I input 011
or 0011
or 0000011
or so on, it gives 9
. I printed the parameter x
immediately after inputting to check where I've gone wrong. It was printing x=9
, not even x=11
. How do I input 0011
as 11
(if I have to) OR how do fix this problem? Here is the Code:
public class Binary
{
long convertDec(long x) {
long res=0;
long k=0;
while(x>0) {
res+=x%10*(long)Math.pow(2,k++);
x=x/10;
}
return res;
}
}
Actually it's part of a larger question, so I am just presenting the required part. I am a Class XII student of ISC board, so please try to explain very simply your answer. I am using the technique of 110=1*2^2+1*2^1+0*2^0
.
Take a look at the following code:
int v3 = 0b11;
System.out.println(v3);
int va = 11;
System.out.println(va);
int vb = 011;
System.out.println(vb);
This will print
3
11
9
That is because 0b11 means 3 in binary. And you can use 0b00000011; and you will still get 3.
11 is 11.
011 is actually an octal value. 1*8^1 + 1*8^0 -> 8 + 1 -> 9