In this Java program, you’ll learn how to Convert Binary Number to Decimal and vice-versa using the Java programming language.
How to Convert Binary Number to Decimal and vice-versa using JAVA?
Example 1: Using custom method
RUN CODE SNIPPETclass Main { public static void main(String[] args) { long num = 11110111; int decimal = convertBinaryToDecimal(num); System.out.println("Binary to Decimal"); System.out.println(num + " = " + decimal); } public static int convertBinaryToDecimal(long num) { int decimalNumber = 0, i = 0; long remainder; while (num != 0) { remainder = num % 10; num /= 10; decimalNumber += remainder * Math.pow(2, i); ++i; } return decimalNumber; } }
OUTPUT:
Binary to Decimal 11110111 = 247
Example 2: Using ParesInt()
RUN CODE SNIPPETclass Main { public static void main(String[] args) { String binary = "01011111"; int decimal = Integer.parseInt(binary, 2); System.out.println(binary + " in binary = " + decimal + " in decimal."); } }
OUTPUT:
01011111 in binary = 95 in decimal.