Home »
C programs »
C number system conversion programs
C program to convert a hexadecimal number into a binary number
Here, we are going to learn how to convert a hexadecimal number into a binary number in C programming language?
Submitted by Nidhi, on July 03, 2021
Problem statement
Here, we will read a hexadecimal number and convert it into a binary number and print the result on the console screen.
C program to convert a hexadecimal number into a binary number
The source code to convert a hexadecimal number into a binary number is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.
// C program to convert a hexadecimal number
// into binary number
#include <stdio.h>
int main()
{
char HexNum[32] = { 0 };
int i = 0;
printf("Enter the Hexadecimal number: ");
scanf("%s", HexNum);
printf("Binary Number: ");
while (HexNum[i]) {
switch (HexNum[i]) {
case '0':
printf("0000");
break;
case '1':
printf("0001");
break;
case '2':
printf("0010");
break;
case '3':
printf("0011");
break;
case '4':
printf("0100");
break;
case '5':
printf("0101");
break;
case '6':
printf("0110");
break;
case '7':
printf("0111");
break;
case '8':
printf("1000");
break;
case '9':
printf("1001");
break;
case 'a':
case 'A':
printf("1010");
break;
case 'b':
case 'B':
printf("1011");
break;
case 'c':
case 'C':
printf("1100");
break;
case 'd':
case 'D':
printf("1101");
break;
case 'e':
case 'E':
printf("1110");
break;
case 'f':
case 'F':
printf("1111");
break;
default:
printf("\nInvalid hexa digit: %c", HexNum[i]);
return 0;
}
i++;
}
return 0;
}
Output
Enter the Hexadecimal number: A123
Binary Number: 1010000100100011
Explanation
Here, we created a character array HexNum and integer variable i. Then we read the hexadecimal number and convert the number into a binary number and printed the result on the console screen.
C Number System Conversion Programs »