C Program to Convert Hexadecimal Number to Binary Number System

  • Write a C program to convert hexadecimal number to binary number system.
  • How to convert hexadecimal number to binary number in C.

Required Knowledge

Hexadecimal number system is a base 16 number system using digits 0 to 9 and A to F, whereas Binary number system is base 2 and using digits 0 and 1. Given an hexadecimal number as input from user convert it to binary number.

For Example

123A in Hexadecimal is equivalent to 0001001000111010 in Binary number system.
Algorithm to convert Hexadecimal to Binary number

  • Create a mapping between hexadecimal digits and binary sequence.
  • Now, replace each hexadecimal digit with it’s corresponding binary sequence as mentioned in below program.

C program to convert a hexadecimal number to binary number

C Program to Convert Hexadecimal Number to Binary Number System

#include <stdio.h>  
#include <string.h>  
   
int main() {  
    char *hexDigitToBinary[16] = {"0000", "0001", "0010", "0011", "0100", "0101", 
 "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"};    
    char hexDigits[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8',
      '9', 'A', 'B', 'C', 'D', 'E', 'F'};
    char hexadecimal[30], binaryNumber[100];   
    int i = 0, j, index=0;  
   
    /* 
     * Take a hexadecimal number as input from user 
     */ 
    printf("Enter a Hexadecimal Number\n");  
    scanf("%s", hexadecimal);
   
    /* 
     * Find he hexadecimal digit in hexDigits and the substitute it
     * with corresponding value in hexDigitToBinary
     */ 
    for(i=0; hexadecimal[i] != '\0'; i++)  {  
        for(j = 0; j < 16; j++){
            if(hexadecimal[i] == hexDigits[j]){
                strcat(binaryNumber, hexDigitToBinary[j]);
            }
        }
    }  
   
    printf("Binary Number : %s", binaryNumber);  
   
    return 0;  
}

Output

Enter a Hexadecimal Number
123A
Binary Number : 0001001000111010
Enter a Hexadecimal Number
11CD
Binary Number : 0001000111001101