C Program to Convert Hexadecimal to Binary

In this tutorial, we will write a C Program to Convert a Hexadecimal Number to Binary Number. Before that, you must have knowledge of the following topics in C.

Binary number

The binary numbers are based on 0 and 1, so it is a base 2 number. They are the combination of 0 and 1. For example, 1001, 110101, etc.

Hexadecimal number

The hexadecimal number is represented with a base of 16. It has digits from 0 to 15 to represent, However after 9 the values are represented in Alphabet till 15 such as 10 is represented as A, 11 as B, 12 as C, 13 as D, 14 as E, and 15 as F.

Input: DF
Output: 11011111

Input: 8D
Output: 10001101

Now let us go through a program for hexadecimal to decimal conversion in C.


C Program to Convert Hexadecimal to Binary

#include <stdio.h>
#define MAX 1000

int main()
{
  char binarynum[MAX], hexadecimalnum[MAX];
  long int i = 0;

  printf("Enter a hexadecimal number: ");
  scanf("%s", hexadecimalnum);

  printf("Equivalent binary value: ");
  while (hexadecimalnum[i])
  {
    switch (hexadecimalnum[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':
        printf("1010");
        break;
      case 'B':
        printf("1011");
        break;
      case 'C':
        printf("1100");
        break;
      case 'D':
        printf("1101");
        break;
      case 'E':
        printf("1110");
        break;
      case 'F':
        printf("1111");
        break;
      case 'a':
        printf("1010");
        break;
      case 'b':
        printf("1011");
        break;
      case 'c':
        printf("1100");
        break;
      case 'd':
        printf("1101");
        break;
      case 'e':
        printf("1110");
        break;
      case 'f':
        printf("1111");
        break;
      default:
        printf("Invalid hexadecimal Number.");
        return 0;
    }

    i++;
  }

  return 0;
}

Output:

Enter a hexadecimal number: 8D
Equivalent binary value: 10001101