Question about Binary to Decimal

  • (2 Pages)
  • +
  • 1
  • 2

18 Replies - 3656 Views - Last Post: 10 February 2013 - 06:43 PM Rate Topic: -----

#1 575Cenna  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 14
  • Joined: 29-July 11

Question about Binary to Decimal

Posted 18 October 2011 - 05:07 PM

I need to write a method that parses a binary number as a string into a decimal integer.
The method header is as follows: public static int binaryToDecimal(String binaryString)

The program should prompt the user to enter a binary string and display the corresponding decimal integer value.
This is a sample of what the program should do:
Enter a binary number string: 1111111111
The decimal value is 1023

Ok I am not sure what to do next, I am thinking that I should try to do a for loop next but its just not working out in my head.

import java.util.Scanner;

public class Exercise09_08 {
  public static void main(String[] args) {
    
  Scanner input = new Scanner(System.in);
    
  // Prompt the user to enter a string
    System.out.print("Enter a binary number string: ");
    String s = input.nextLine();
    System.out.println("The decimal value is " + binaryToDecimal(s));
  }

  public static int binaryToDecimal(String binaryString) {

  }

  }
 }



Thanks

Is This A Good Question/Topic? 0
  • +

Replies To: Question about Binary to Decimal

#2 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8324
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Question about Binary to Decimal

Posted 18 October 2011 - 05:14 PM

Simply init a value to 0
Loop throught you String digit by digit
multiply value by 2
add 0 or 1 depending if the digit is '0' or '1'

int convert(String binary) {
   int value = 0;
   for(int i = 0; i < binary.length; ++i) {
      value *= 2;
      value += (int) (binary.charAt(i) - '0');
   }
   return value;
}


Was This Post Helpful? 2
  • +
  • -

#3 blackcompe  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1150
  • View blog
  • Posts: 2,528
  • Joined: 05-May 05

Re: Question about Binary to Decimal

Posted 18 October 2011 - 05:14 PM

Well, just to let you know, Integer.parseInt(String, int) will do that for you. If you can't use that you'll need a for loop in which you'll create a summation of 2^i if index i is a 1 in the string.
Was This Post Helpful? 0
  • +
  • -

#4 575Cenna  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 14
  • Joined: 29-July 11

Re: Question about Binary to Decimal

Posted 18 October 2011 - 05:29 PM

View Postpbl, on 18 October 2011 - 05:14 PM, said:

Simply init a value to 0
Loop throught you String digit by digit
multiply value by 2
add 0 or 1 depending if the digit is '0' or '1'

int convert(String binary) {
   int value = 0;
   for(int i = 0; i < binary.length; ++i) {
      value *= 2;
      value += (int) (binary.charAt(i) - '0');
   }
   return value;
}


Thank you for your help, and I am really trying to understand this stuff. Why multiply value by 2?
Was This Post Helpful? 0
  • +
  • -

#5 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8324
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Question about Binary to Decimal

Posted 18 October 2011 - 05:36 PM

Binary = 2

What is 110001 ?

it is:
x = 1;
x = x * 2 + 1
x = x * 2 + 0
x = x * 2 + 0
x = x * 2 + 0
x = x * 2 + 1

as 12345 is :
x = 1
x = x * 10 + 2 = 12
x = x * 10 + 3 = 123
x = x * 10 + 4 = 1234
x = x * 10 + 5 = 12345
Was This Post Helpful? 1
  • +
  • -

#6 575Cenna  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 14
  • Joined: 29-July 11

Re: Question about Binary to Decimal

Posted 18 October 2011 - 05:40 PM

View Postpbl, on 18 October 2011 - 05:36 PM, said:

Binary = 2

What is 110001 ?

it is:
x = 1;
x = x * 2 + 1
x = x * 2 + 0
x = x * 2 + 0
x = x * 2 + 0
x = x * 2 + 1

as 12345 is :
x = 1
x = x * 10 + 2 = 12
x = x * 10 + 3 = 123
x = x * 10 + 4 = 1234
x = x * 10 + 5 = 12345

That definitely makes sense. I hope I get the hang of this soon.
Was This Post Helpful? 0
  • +
  • -

#7 CasiOo  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 1376
  • View blog
  • Posts: 3,027
  • Joined: 05-April 11

Re: Question about Binary to Decimal

Posted 18 October 2011 - 05:55 PM

Every number has a position value, and you use this to calculate the result.

For example if we take the following binary number 1010
then the position values are (from left to right): 8, 4, 2, 1

You can write the positionvalue as a power of 2 using the position of the number.
value = binaryNumber * 2^position



This leads to this piece of code
	public static long binaryToDecimal(String binary) {
		long result = 0;
		for (int i=0; i<binary.length(); i++) 
			result += (int) (binary.charAt( i ) - '0') * Math.pow( 2, binary.length() - i - 1 );
		
		return result;
	}


Was This Post Helpful? 1
  • +
  • -

#8 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8324
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Question about Binary to Decimal

Posted 18 October 2011 - 06:01 PM

not a reallky good idea to imply Math.pow() in here
Will have to translate your int to double
call the log10 to perform the operation

And if ever you do it with long, instead of int, you might lost precison in the double/long conversion and end up with an erroneous answer
* and + a lot more efficient and accurate algorithm that your calls to Math.poser()
Was This Post Helpful? 1
  • +
  • -

#9 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8324
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Question about Binary to Decimal

Posted 18 October 2011 - 06:15 PM

If you were a production analyst which code would you prefer to support ?
	for (int i=0; i<binary.length(); i++) 
		result += (int) (binary.charAt( i ) - '0') * Math.pow( 2, binary.length() - i - 1 );
		


or
   for(int i = 0; i < binary.length(); ++i) {
      value *= 2;
      value += (int) (binary.charAt(i) - '0');
   }


:)
*Edited missing () after my length

This post has been edited by pbl: 18 October 2011 - 06:48 PM

Was This Post Helpful? 1
  • +
  • -

#10 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8324
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Question about Binary to Decimal

Posted 18 October 2011 - 06:34 PM

And I am not talking about performance issues :)


public class Power {

	public static void main(String[] args) {
        String str = "101010101010101010101010101010";
        long begin, now;
        int x;

        begin = System.currentTimeMillis();
		for(int i = 0; i < 1000000; ++i)
        	x = casio(str);
        now = System.currentTimeMillis();
        System.out.println("Casio's algorithm: " + (now-begin) + " ms");
        
        begin = System.currentTimeMillis();
		for(int i = 0; i < 1000000; ++i)
        	x = pbl(str);
        now = System.currentTimeMillis();
        System.out.println("  pbl's algorithm: " + (now-begin) + " ms");
	}

	static int casio(String binary) {
		int result = 0;
		for (int i=0; i<binary.length(); i++) 
			result += (int) (binary.charAt( i ) - '0') * Math.pow( 2, binary.length() - i - 1 );

		return result;
	}

	static int pbl(String binary) {
		int value = 0;
		for(int i = 0; i < binary.length(); ++i) {
			   value *= 2;
			   value += (int) (binary.charAt(i) - '0');
			}
        return value;
	}
}


yields
Casio's algorithm: 9821 ms
  pbl's algorithm: 45 ms


:^:
Was This Post Helpful? 0
  • +
  • -

#11 Sheph  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 432
  • View blog
  • Posts: 1,020
  • Joined: 12-October 11

Re: Question about Binary to Decimal

Posted 18 October 2011 - 06:42 PM

pbl, your algorithm is so efficient and simple, that it is kinda hard to understand. Most people are taught to convert binary to decimal in high school math classes starting from the end of the array rather than the beginning. So to understand what every line in your code is doing takes an extra depth of understanding. I actually had to say your algorithm was wrong and try to prove it to myself before I could understand that it is correct and WHY it is correct. Lol Thanks for that one : )
Was This Post Helpful? 0
  • +
  • -

#12 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8324
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Question about Binary to Decimal

Posted 18 October 2011 - 06:45 PM

As far as the rounding error occurs because Math.power() uses double :)

public class Power {

	public static void main(String[] args) {
        String str = "101010101010101010101010101010";
        long l1, l2;
        
        for(int i = 0; i < 16; ++i) {
        	l1 = casio(str);
        	l2 = pbl(str);
        	System.out.printf("pow: %20d * and +: %20d for %s\n", l1, l2, str);
        	str += "10";
        }

	}

	static long casio(String binary) {
		long result = 0;
		for (int i=0; i<binary.length(); i++) 
			result += (long) (binary.charAt( i ) - '0') * Math.pow( 2, binary.length() - i - 1 );

		return result;
	}

	static long pbl(String binary) {
		long value = 0;
		for(int i = 0; i < binary.length(); ++i) {
			   value *= 2;
			   value += (long) (binary.charAt(i) - '0');
			}
        return value;
	}
}


yields
pow:            715827882 * and +:            715827882 for 101010101010101010101010101010
pow:           2863311530 * and +:           2863311530 for 10101010101010101010101010101010
pow:          11453246122 * and +:          11453246122 for 1010101010101010101010101010101010
pow:          45812984490 * and +:          45812984490 for 101010101010101010101010101010101010
pow:         183251937962 * and +:         183251937962 for 10101010101010101010101010101010101010
pow:         733007751850 * and +:         733007751850 for 1010101010101010101010101010101010101010
pow:        2932031007402 * and +:        2932031007402 for 101010101010101010101010101010101010101010
pow:       11728124029610 * and +:       11728124029610 for 10101010101010101010101010101010101010101010
pow:       46912496118442 * and +:       46912496118442 for 1010101010101010101010101010101010101010101010
pow:      187649984473770 * and +:      187649984473770 for 101010101010101010101010101010101010101010101010
pow:      750599937895082 * and +:      750599937895082 for 10101010101010101010101010101010101010101010101010
pow:     3002399751580330 * and +:     3002399751580330 for 1010101010101010101010101010101010101010101010101010
pow:    12009599006321322 * and +:    12009599006321322 for 101010101010101010101010101010101010101010101010101010
// start to fail here 
pow:    48038396025285288 * and +:    48038396025285290 for 10101010101010101010101010101010101010101010101010101010
pow:   192153584101141152 * and +:   192153584101141162 for 1010101010101010101010101010101010101010101010101010101010
pow:   768614336404564608 * and +:   768614336404564650 for 101010101010101010101010101010101010101010101010101010101010


Was This Post Helpful? 2
  • +
  • -

#13 blackcompe  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1150
  • View blog
  • Posts: 2,528
  • Joined: 05-May 05

Re: Question about Binary to Decimal

Posted 18 October 2011 - 06:45 PM

View PostSheph, on 18 October 2011 - 07:42 PM, said:

pbl, converting a 128-bit number takes 35 secs using Math.pow! Jeez....

Converting a 30 bits long number 1 million times takes 9.8 seconds
* and + 0.045 seconds
:^:

This post has been edited by pbl: 18 October 2011 - 06:53 PM

Was This Post Helpful? 0
  • +
  • -

#14 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8324
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Question about Binary to Decimal

Posted 18 October 2011 - 06:47 PM

View PostSheph, on 18 October 2011 - 09:42 PM, said:

pbl, your algorithm is so efficient and simple, that it is kinda hard to understand. Most people are taught to convert binary to decimal in high school math classes starting from the end of the array rather than the beginning. So to understand what every line in your code is doing takes an extra depth of understanding. I actually had to say your algorithm was wrong and try to prove it to myself before I could understand that it is correct and WHY it is correct. Lol Thanks for that one : )

My pleasure, as I have already said more than once, Assembler code should be mandatory at every level :)

And the last 35 years I made my living by fine tuning applications all over the world for performances mostly on OpenVMS, that helps.

This post has been edited by pbl: 18 October 2011 - 06:55 PM

Was This Post Helpful? 0
  • +
  • -

#15 CasiOo  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 1376
  • View blog
  • Posts: 3,027
  • Joined: 05-April 11

Re: Question about Binary to Decimal

Posted 19 October 2011 - 02:14 AM

Our teacher actually showed us the algorithm you posted pbl ^^

I didn't really think about Math.pow having such big of an impact. I knew it would be slower, but I didn't think the precision would get worse.
Was This Post Helpful? 1
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2