C Program to Convert Binary Number to Hexadecimal Number System

  • Write a C program to convert binary number to hexadecimal number system.
  • Wap in C to convert a base 2 number to a base 16 number.

Required Knowledge

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

For Example
10001111 in Binary is equivalent to 8F in hexadecimal number.

C program to convert a decimal number to hexadecimal number

#include <stdio.h>  
#include <string.h>  
  
int main() {  
    int hexDigitToBinary[16] = {0, 1, 10, 11, 100, 101, 110, 111, 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 hexaDecimalNumber[20];    
    long binaryNumber;  
    int position, i, digits;  
      
    /* 
     * Take a binary number as input from user 
     */  
    printf("Enter a Binary Number\n");  
    scanf("%ld", &binaryNumber);  
    
    position = 0;  
      
    /* Convert a Hexadecimal Number to Binary Number */
    while(binaryNumber!=0) {
     /*get the last 4 binay digits */
        digits = binaryNumber % 10000;  
        for(i=0; i<16; i++) {
            if(hexDigitToBinary[i] == digits) {
                hexaDecimalNumber[position] = hexDigits[i];
                position++;  
                break;  
            }  
        }  
  
        binaryNumber /= 10000;  
    }  
  
    hexaDecimalNumber[position] = '\0';  
    strrev(hexaDecimalNumber);  
  
    printf("Hexadecimal Number : %s", hexaDecimalNumber);  
  
    return 0;  
}
Program Output
Enter a Binary Number
10010101
Hexadecimal Number : 95
Enter a Binary Number
10001111
Hexadecimal Number : 8F

Related Topics
C program to convert binary numbers to octal number using function
C program to convert a octal number to decimal number system
C program to convert octal number to hexadecimal number system
C program to convert decimal number to hexadecimal number system
C program to convert hexadecimal number to decimal number system
C program to convert temperature from celsius to fahrenheit
C program to convert binary number to decimal number system
C program to convert octal number to binary number system
C program to make a simple calculator using switch statement
List of all C programs