# Question about Binary to Decimal

• (2 Pages)
• 1
• 2

## 18 Replies - 6038 Views - Last Post: 10 February 2013 - 06:43 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=251893&amp;s=9072ca312087963691511519a0b1a68b&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 575Cenna

Reputation: 1
• 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

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

Reputation: 8362
• Posts: 31,955
• 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;
}

```

### #3 blackcompe

• D.I.C Lover

Reputation: 1156
• Posts: 2,538
• 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.

### #4 575Cenna

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

## Re: Question about Binary to Decimal

Posted 18 October 2011 - 05:29 PM

pbl, 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?

### #5 pbl

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

Reputation: 8362
• Posts: 31,955
• 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

### #6 575Cenna

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

## Re: Question about Binary to Decimal

Posted 18 October 2011 - 05:40 PM

pbl, 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.

### #7 CasiOo

• D.I.C Lover

Reputation: 1471
• Posts: 3,266
• 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;
}

```

### #8 pbl

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

Reputation: 8362
• Posts: 31,955
• 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()

### #9 pbl

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

Reputation: 8362
• Posts: 31,955
• 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

### #10 pbl

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

Reputation: 8362
• Posts: 31,955
• 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

```

### #11 Sheph

• D.I.C Lover

Reputation: 444
• Posts: 1,030
• 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 : )

### #12 pbl

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

Reputation: 8362
• Posts: 31,955
• 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

```

### #13 blackcompe

• D.I.C Lover

Reputation: 1156
• Posts: 2,538
• Joined: 05-May 05

## Re: Question about Binary to Decimal

Posted 18 October 2011 - 06:45 PM

Sheph, 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

### #14 pbl

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

Reputation: 8362
• Posts: 31,955
• Joined: 06-March 08

## Re: Question about Binary to Decimal

Posted 18 October 2011 - 06:47 PM

Sheph, 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

### #15 CasiOo

• D.I.C Lover

Reputation: 1471
• Posts: 3,266
• 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.