Convert a binary string to decimal in Java
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
public class Main { public static void main(String[] args) { String binary = "11111111"; int i = Integer.parseInt(binary, 2); System.out.println(i); // 255 } } |
The maximum value of a signed integer is 231-1, which is equivalent to 01111111 11111111 11111111 11111111 in binary. This is demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 |
public class Main { public static void main(String[] args) { String binary = "01111111111111111111111111111111"; int i = Integer.parseInt(binary, 2); System.out.println(i); // 2147483647 } } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 |
public class Main { public static void main(String[] args) { String binary = "11111111111111111111111111111111"; int i = (int) Long.parseLong(binary, 2); System.out.println(i); // -1 } } |
Alternatively, you can also use the Integer.parseUnsignedInt() method to convert the binary string 11111111 11111111 11111111 11111111 to a decimal value.
|
1 2 3 4 5 6 7 8 9 10 11 |
public class Main { public static void main(String[] args) { String binary = "11111111111111111111111111111111"; int i = Integer.parseUnsignedInt(binary, 2); System.out.println(i); // -1 } } |
2. Using Custom Routine
You can even write a custom routine for this simple task. Here’s how the code would look like:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
public class Main { public static int toInteger(String binary) { long decimal = 0; for (int i = binary.length() - 1; i >= 0; i--) { if (binary.charAt(i) == '1') { decimal += Math.pow(2, (binary.length() - i - 1)); } } return (int)decimal; } public static void main(String[] args) { String binary = "11111111111111111111111111111111"; int i = toInteger(binary); System.out.println(i); // -1 } } |
That’s all about converting a binary string to decimal in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)