1. Member
Join Date
Jul 2013
Location
india
Posts
15
Rep Power
0

## BinaryToDecimal

Java Code:
```package com.necre.oops5;

import java.util.Scanner;

public class BinaryToDecimal {

public static void main(String[] args) {

Scanner scanner=new Scanner(System.in);
System.out.println("enter a binary no:");
String no=scanner.next();

convert(no);
}

public static void convert(String no) {

int decimalNo=0;
int temp=1;
int range=no.length()-1;

for (int index = range; index >= 0; index--) {

if (index==range) {
decimalNo=no.charAt(index)*2*temp;
System.out.println(no.charAt(index)+"*"+2+"*"+temp+":"+decimalNo);
}
else {
decimalNo=decimalNo+no.charAt(index)*2*temp;
System.out.println(no.charAt(index)+"*"+2+"*"+temp+":"+decimalNo);
temp=temp*2;
}
}
System.out.println("decimal no:"+decimalNo);
}

}```

I want to convert binary no to decimal no ........but i did some mistake which is giving some wrong output ...........where is that mistake...

output:

enter a binary no:
1010
0*2*1:96
1*2*1:194
0*2*2:386
1*2*4:778
decimal no:778

2. ## Re: BinaryToDecimal

I didn't look at your code but from the output it seems you are misunderstanding how the conversion works.
Below ^ means "raised to the power of"
1010 = (1*2^3) + (0*2^2) + (1*2^1) + (0*2^0)
= (1*8) + (0*4) + (1*2) + (0*1) // remember that anything raised to the power of 0 is 1.
= 8 + 0 + 2 + 0
= 10

You need to rethink your algorithm. You should be able to do this with a single loop.

3. ## Re: BinaryToDecimal

Now I have looked at the code. Apart from getting the power wrong and not doing any addition. You are also multiplying the char (its ascii value) and not its numeric value

4. ## Re: BinaryToDecimal

You can also use
Java Code:
`Integer.toBinaryString(intValue)`

5. ## Re: BinaryToDecimal

OP is trying the opposite conversion: binary to integer. Besides I assume this is an assignment where they must write the code themselves.

6. Member
Join Date
Jul 2013
Location
india
Posts
15
Rep Power
0

## Re: BinaryToDecimal

How can I avoid multiplying by ascii value ............... any converson require?????????modify my code .......

7. ## Re: BinaryToDecimal

Look at the Character class. It has a method that can convert '1' to 1.

8. Member
Join Date
Jul 2013
Location
india
Posts
15
Rep Power
0

## Re: BinaryToDecimal

In Character class getNumeric() method is there ............ but i used String instead of Character class.

9. ## Re: BinaryToDecimal

As long as it works!

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•