views:

295

answers:

4

whats a way to convert a binary string to a decimal integer without using

Integer.parseInt

??

A: 

Please explain why

parseInt("1100110", 2)

(which returns 102) would not do exactly what you need?

Otherwise, start from the right of the string, take each bit in turn and compute the value.

0

plus

2

plus

4

and so on

djna
+1  A: 

you can do it the manual way, start from the left, if its a 1 add 1, then multiply by 2, keep going until String is done

public static long toDecimal(String binary)
{
long decimal=0L;
for (int i = 0, n = binary.length(); i < n; i++)
  {
  if ( binary.charAt(i) == '1' )
    decimal++;
  if ( i != n-1 )
    decimal*=2L;
  }
return decimal;
}
Peter
A: 

If a default way is available then what is the need to solve it programatically

subbu
you might just learn from it
Toad
+1  A: 

Either

( int ) Long.parseLong ( "1001", 2 )

or

( new BigInteger ( "1001", 2 ) ).intValue()

convert a binary string to an int without using Integer.parseInt()

Pete Kirkham