This example shows the conversion of Decimal to Binary & Binary to Decimal in Java.
The toBinary() method in BinaryConversion class uses the recursion logic of modulo(%) 2 of given number(which is reminder), and calls the same method recursively with number/2( from 512>>2 =256) , until the reminder is one.
The toDecimal() method uses the recursion logic by calling the same method and add the result of last digit multiplied by 2.,
Binary Conversions:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
public class BinaryConversion { public static void main(String[] args) { Integer a = 4; // 0000 0100 int b = -20; // 0001 0100 toBinary(512); System.out.println(); System.out.println(“ ** ** ”); System.out.println(toDecimal(“1000000000”)); } public static void toBinary(int number) { if (number <= 1) { System.out.print(number); return; } int reminder = number % 2; toBinary(number >> 1); System.out.print(reminder); } public static int toDecimal(String binaryNumber) { if (binaryNumber == null || binaryNumber.length() == 0) { return 0; } String currentBinaryDigit = binaryNumber.substring(0, 1); String remainingPartofBinaryNumber = binaryNumber.substring(1); return (Integer.parseInt(currentBinaryDigit) * (int) Math.pow(2, binaryNumber.length()– 1)) + toDecimal(remainingPartofBinaryNumber); } |
Result:
1 2 3 |
1000000000 **** 512 |