whats a way to convert a binary string to a decimal integer without using
Integer.parseInt
??
whats a way to convert a binary string to a decimal integer without using
Integer.parseInt
??
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
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;
}
If a default way is available then what is the need to solve it programatically
Either
( int ) Long.parseLong ( "1001", 2 )
or
( new BigInteger ( "1001", 2 ) ).intValue()
convert a binary string to an int
without using Integer.parseInt()