EN
Java - convert binary String to int
5
points
Short solution:
String binaryString = "101";
int number = Integer.parseInt(binaryString, 2);
System.out.println(number); // 5
The best way to convert binary String to int in java is to use Integer.parseInt() method.
Syntax:
Integer.parseInt(String binaryString, int radix)
1. Simple example
public class Example1 {
public static void main(String[] args) {
String binaryString = "101";
int number = Integer.parseInt(binaryString, 2);
System.out.println(number); // 5
}
}
Output:
5
2. Convert couple of different binary strings to int
public class Example2 {
public static void main(String[] args) {
System.out.println( Integer.parseInt("00000000", 2) ); // 0
System.out.println( Integer.parseInt("00000101", 2) ); // 5
System.out.println( Integer.parseInt("00001000", 2) ); // 8
System.out.println( Integer.parseInt("00001100", 2) ); // 12
System.out.println( Integer.parseInt("00010000", 2) ); // 16
System.out.println( Integer.parseInt("11111111", 2) ); // 255
}
}
Output:
0
5
8
12
16
255
3. Convert binary string to int in loop - from 0 to 16
In this example we convert binary string to int in loop from 0 to 16 and then we print both binary and decimal representations of given number.
public class Example3 {
public static void main(String[] args) {
for (int number = 0; number <= 16; number++) {
String binaryString = Integer.toBinaryString(number);
String format = String.format("%8s", binaryString);
String withLeadingZeros = format.replace(' ', '0');
int backToNumber = Integer.parseInt(binaryString, 2);
System.out.println(withLeadingZeros + " - " + backToNumber);
}
}
}
Output:
00000000 - 0
00000001 - 1
00000010 - 2
00000011 - 3
00000100 - 4
00000101 - 5
00000110 - 6
00000111 - 7
00001000 - 8
00001001 - 9
00001010 - 10
00001011 - 11
00001100 - 12
00001101 - 13
00001110 - 14
00001111 - 15
00010000 - 16