Explain Codes LogoExplain Codes Logo

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

java
binary-conversion
base-10-integer
two-complement-notation
Alex KataevbyAlex Kataev·Jan 24, 2025
TLDR

To convert a binary String to an integer, we use the Integer.parseInt(binaryString, 2) method. The radix 2 specifies binary to decimal conversion:

int decimal = Integer.parseInt("1101", 2); // Outputs 13, not your lucky number

For longer binary strings or binaries representing negative numbers, Long.parseLong() is an excellent ally:

long decimalLong = Long.parseLong(binaryString, 2); // {Insert obligatory size matters joke here}

The practical guide to negativeness and prolonged bins

When working with binary strings that represent negative numbers, we need sign extension. In Java, negative binary numbers are represented using two's complement notation, with the most significant bit acting as a sign bit. That's not something to sign off lightly!

String signedBinary = "11111111111111111111111111101011"; // Represents -21. Yes, in the binary world, 21 is not always fun. long decimal = Long.parseLong(signedBinary, 2);

When bytes bite back — large string handling

If you like living life on the fast lane like I do, bit shifts can be more efficient than Math.pow. If you're dealing with an unsigned number, manual conversion of each character and bit shift accumulation is the Usain Bolt of methods:

String unsignedBinary = "1011"; int result = 0; for (int i = 0; i < unsignedBinary.length(); i++) { result = (result << 1) + (unsignedBinary.charAt(i) - '0'); // << is not a typo, I swear. }

Down the rabbit hole of conversions — advanced considerations

Know your limits: data bounds

Keep in mind the numeric boundaries. An Integer has its limits (2^31-1), and beyond that, BigInteger is your only friend against the formidable NumberFormatException.

Test, test, and test

Never trust your code on the face value. Thorough test cases with binary strings of diverse lengths and values ensure it handles the edge cases efficiently.

Leading zeros: the unsung heroes

The leading zeros are the unsung heroes of the binary to decimal conversion process. Even though they don't get the credit, it's crucial to remember that they quietly change the game without altering the final result.