This post will discuss how to convert a binary string to decimal in Java.

1. Using Integer.parseInt() method

To convert a base 2 string to a base 10 integer, you can use the overloaded version of the Integer#parseInt() method, which allows you to specify the radix. Following is a simple example demonstrating its usage to parse a string as a signed integer in the specified radix.

Download  Run Code

 
The maximum value of a signed integer is 231-1, which is equivalent to 01111111 11111111 11111111 11111111 in binary. This is demonstrated below:

Download  Run Code

 
If you need to convert the binary string 11111111 11111111 11111111 11111111 to corresponding decimal value -1, the above method won’t work. To convert -1 from binary to decimal, you may want to use the Long.parseLong() method, as shown below:

Download  Run Code

 
Alternatively, you can also use the Integer.parseUnsignedInt() method to convert the binary string 11111111 11111111 11111111 11111111 to a decimal value.

Download  Run Code

2. Using Custom Routine

You can even write a custom routine for this simple task. Here’s how the code would look like:

Download  Run Code

That’s all about converting a binary string to decimal in Java.