Aunteek Naser
Aunteek Naser

Reputation: 5

How to convert from binary to decimal in java?

I am trying to write code in java that takes a binary string from the user, then using arrays(?), makes it a base 10 integer. My friend trying to help me wrote this, but there is no variable "c" and i do not have any idea what he tried to do.

 //Binary Conversion
 System.out.println("Enter a value in binary to convert to decimal");
 int binary = 
 int decimalValue = Integer.parseInt(c, 2);

Before this, i already had skeleton code and a declared keyboard scanner, so I assume that

int binary

is followed by

kbReader.nextInt();

Any help?

Upvotes: 0

Views: 815

Answers (2)

Somasundar Kanakaraj
Somasundar Kanakaraj

Reputation: 11

    **//Conversion between Binary & Decimal**
    public static void main(String args[]){
    **//Binary to Decimal**
            String BtD = "10001110";
            if(isBinary(Integer.parseInt(BtD))){
                System.out.println("Binary Value is ==>> "+Integer.parseInt(BtD));
                System.out.println("Decimal Value is ==>> "+Integer.parseInt(BtD,2));
            }else{
                System.out.println("Not an binary no");
            }
    **//Decimal to Binary**     
            int DtB = 142;
            System.out.println("Decimal Value is ==>> "+DtB);
            System.out.println("Binary Value is ==>> "+Integer.toBinaryString(DtB));
        }
**//To check entered value is binary or not**
        public static boolean isBinary(int number){
            boolean status = true;
            while(true){
                if(number == 0){
                    break;
                }else{
                    int temp = number % 10;
                    if(temp > 1){
                        status = false;
                        break;
                    }
                    number = number /10;
                }
            }
            return status;
        }

Upvotes: 1

emad omara
emad omara

Reputation: 528

You can read the input as String using scanner.next(); then use the Integer parse method as you said which will take the input string and the wanted radix which is in this case =2

Upvotes: 1

Related Questions