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
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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 | #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