EN
Java - convert binary String to int
5 points
Short solution:
xxxxxxxxxx
1
String binaryString = "101";
2
int number = Integer.parseInt(binaryString, 2);
3
4
System.out.println(number); // 5
The best way to convert binary String to int in java is to use Integer.parseInt() method.
Syntax:
xxxxxxxxxx
1
Integer.parseInt(String binaryString, int radix)
xxxxxxxxxx
1
public class Example1 {
2
3
public static void main(String[] args) {
4
5
String binaryString = "101";
6
int number = Integer.parseInt(binaryString, 2);
7
System.out.println(number); // 5
8
}
9
}
Output:
xxxxxxxxxx
1
5
xxxxxxxxxx
1
public class Example2 {
2
3
public static void main(String[] args) {
4
5
System.out.println( Integer.parseInt("00000000", 2) ); // 0
6
System.out.println( Integer.parseInt("00000101", 2) ); // 5
7
System.out.println( Integer.parseInt("00001000", 2) ); // 8
8
System.out.println( Integer.parseInt("00001100", 2) ); // 12
9
System.out.println( Integer.parseInt("00010000", 2) ); // 16
10
System.out.println( Integer.parseInt("11111111", 2) ); // 255
11
}
12
}
Output:
xxxxxxxxxx
1
0
2
5
3
8
4
12
5
16
6
255
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.
xxxxxxxxxx
1
public class Example3 {
2
3
public static void main(String[] args) {
4
5
for (int number = 0; number <= 16; number++) {
6
7
String binaryString = Integer.toBinaryString(number);
8
9
String format = String.format("%8s", binaryString);
10
String withLeadingZeros = format.replace(' ', '0');
11
12
int backToNumber = Integer.parseInt(binaryString, 2);
13
14
System.out.println(withLeadingZeros + " - " + backToNumber);
15
}
16
}
17
}
Output:
xxxxxxxxxx
1
00000000 - 0
2
00000001 - 1
3
00000010 - 2
4
00000011 - 3
5
00000100 - 4
6
00000101 - 5
7
00000110 - 6
8
00000111 - 7
9
00001000 - 8
10
00001001 - 9
11
00001010 - 10
12
00001011 - 11
13
00001100 - 12
14
00001101 - 13
15
00001110 - 14
16
00001111 - 15
17
00010000 - 16