Algorithm to Convert a Decimal to Binary Number

There is an algorithm that can be followed to convert a Decimal to Binary Number as mentioned below:

  1. Take the input decimal number.
  2. If the number is 0, return 0 as the binary equivalent.
  3. Initialize an empty string to store the binary digits.
  4. Divide the decimal number by 2 and get the quotient and remainder.
  5. Convert the remainder to a string and append it to the binary string.
  6. Set the decimal number to the quotient obtained in step 4.
  7. Repeat steps 4-6 until the decimal number becomes 0.
  8. Reverse the binary string obtained in steps 3-7.
  9. Return the reversed binary string.

This algorithm uses the division method to convert a decimal number to binary. At each step, the remainder is computed and appended to the binary string. The quotient becomes the new decimal number for the next iteration. Finally, the binary string is reversed to get the correct binary equivalent of the decimal number.

Below is the implementation of the above algorithm

Java




// Java Program for Hexadecimal to
// Decimal Conversion
  
// Driver Class
public class HexToDec {
    // main function
    public static void main(String[] args)
    {
        String hex1 = "1AB";
        String hex2 = "1A";
        int dec1 = hexToDec(hex1);
        int dec2 = hexToDec(hex2);
        System.out.println(hex1 + " in decimal is " + dec1);
        System.out.println(hex2 + " in decimal is " + dec2);
    }
  
    private static int hexToDec(String hex)
    {
        int len = hex.length();
        int dec = 0;
        for (int i = 0; i < len; i++) {
            char c = hex.charAt(i);
            int digit = Character.digit(c, 16);
            dec = dec * 16 + digit;
        }
        return dec;
    }
}


Output

1AB in decimal is 427
1A in decimal is 26

The complexity of the above method

Time complexity: O(log n), where n is the input decimal number. 
Auxiliary Space: O(log n),



Java Program For Hexadecimal to Decimal Conversion

Given a Hexadecimal number N, convert N into an equivalent decimal number i.e. convert the number with base value 16 to base value 10. The decimal number system uses 10 digits 0-9 and the Hexadecimal number system uses 0-9, A-F to represent any numeric value.

Illustration: 

Input : 1AB
Output: 427
Input : 1A
Output: 26

Similar Reads

Approach to Convert Hexadecimal to Decimal Conversion

The approach to implementing the conversion is mentioned below:...

Programs to Convert Hexadecimal to Decimal Conversion

Below is the implementation of the above approach:...

Algorithm to Convert a Decimal to Binary Number:

...

Contact Us