19 Aug How to Convert binary to decimal in Java
To convert binary to decimal in Java, let us see an example first. Let’s say we have the following binary:
1 2 3 |
0100 |
To get the decimal number from the binary, use the parseInt() method. The syntax is as follows:
1 2 3 |
static int parseInt(String str, int radix) |
Here, str is the binary value as string and radix should be 2 for binary.
Let us now see an example to convert binary to decimal in Java:
Example 1
1 2 3 4 5 6 7 8 9 10 11 |
public class Example { public static void main(String args[] ) { String str = "0100"; System.out.println("Converting Binary to Decimal = "+Integer.parseInt(str, 2)); } } |
Output
1 2 3 |
Converting Binary to Decimal = 10 |
Example 2
1 2 3 4 5 6 7 8 9 10 11 |
public class Example { public static void main(String args[] ) { String str = "111111"; System.out.println("Converting Binary to Decimal = "+Integer.parseInt(str, 2)); } } |
Output
1 2 3 |
Converting Binary to Decimal = 63 |
No Comments