How to convert a Binary String to a base 10 integer in Java

dwwilson66 picture dwwilson66 · Apr 16, 2012 · Viewed 201.4k times · Source

I have an array of Strings that represent Binary numbers (without leading zeroes) that I want to convert to their corresponding base 10 numbers. Consider:

binary 1011 becomes integer 11
binary 1001 becomes integer 9
binary   11 becomes integer 3   etc. 

What's the best way to proceed? I've been exploring java.lang.number.* without finding a direct conversion method. Integer.parseInt(b) yields an integer EQUAL to the String...e.g., 1001 becomes 1,001 instead of 9...and does not seem to include a parameter for an output base. toBinaryString does the conversion the wrong direction. I suspect I'll need to do a multistep conversion, but can't seem to find the right combination of methods or subclasses. I'm also not sure the extent to which leading zeros or lack thereof will be an issue. Anyone have any good directions to point me?

Answer

Matt Ball picture Matt Ball · Apr 16, 2012

You need to specify the radix. There's an overload of Integer#parseInt() which allows you to.

int foo = Integer.parseInt("1001", 2);