Results 1 to 9 of 9
Thread: BinaryToDecimal
- 08-22-2013, 05:00 AM #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
- 08-22-2013, 05:36 AM #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.
- 08-22-2013, 05:45 AM #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
- 08-22-2013, 05:51 AM #4
Re: BinaryToDecimal
You can also use
Java Code:Integer.toBinaryString(intValue)
- 08-22-2013, 05:53 AM #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.
- 08-23-2013, 02:17 AM #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 .......
- 08-23-2013, 03:09 AM #7
Re: BinaryToDecimal
Look at the Character class. It has a method that can convert '1' to 1.
- 08-23-2013, 03:51 AM #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.
- 08-23-2013, 04:54 AM #9
Similar Threads
-
Help with BinarytoDecimal programme
By Thompson in forum New To JavaReplies: 3Last Post: 02-23-2011, 10:43 PM
Bookmarks