soumya_sarkar.19
soumya_sarkar.19

Reputation: 13

Conversion of 011 binary to 3 decimal

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.

Upvotes: 0

Views: 1598

Answers (2)

Likhil Maiya
Likhil Maiya

Reputation: 1

import java.util.*;

public class bindec { long bin,dec;

bindec()
{
    bin=0;
    dec=0;
}

void readbin()
{
    Scanner sc=new Scanner(System.in);
    System.out.println("Enter a binary number:");
    bin=sc.nextLong();
}
int i=0;
long convertDec(long b)
{
    if(b==0)
    {
        return 0;
    }
    else
    {
        int d=(int)b%10;
        dec=dec+(d*(int)Math.pow(2,i));
        i=i+1;
        return convertDec(b/10);
    }
}

void show()
{
    convertDec(bin);
    System.out.println("The dec is:"+dec);

}

public static void main(String args[])
{
    bindec obj=new bindec();
    obj.readbin();
    obj.show();
}

}

Upvotes: 0

Alexandre Santos
Alexandre Santos

Reputation: 8338

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

Upvotes: 6

Related Questions