In this tutorial, we will write a C Program to Convert a Binary Number to Hexadecimal 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: 11011111
Output: DF
Input: 10001101
Output: 8D
Now let us go through a program for Binary to hexadecimal conversion in C.
C Program to Convert Binary to Hexadecimal
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #include <stdio.h> #include <conio.h> int main() { long int binarynum, hexadecimalnum = 0, i = 1, rem; printf("Enter a Binary number: "); scanf("%ld", &binarynum); while (binarynum != 0) { rem = binarynum % 10; hexadecimalnum = hexadecimalnum + rem * i; i = i * 2; binarynum = binarynum / 10; } printf("Equivalent Hexadecimal number: %lX", hexadecimalnum); getch(); return 0; } |
Output:
Enter a Binary number: 10001101
Equivalent Hexadecimal number: 8D