WAP to convert Binary to Hexadecimal number system

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

·                     C printf and scanf functions
·                     While loop in C
·                     For loop in C
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

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
#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

Comments

Most Viewed

Write C program to enter any year and check whether year is leap year or not using conditional/ternary operator.

WAP to input week number and print week day name.

C Program to Find Third Angle of a Triangle