How to convert binary to Hex by using C language?


Binary numbers are represented in 1’s and 0’s.

Hexadecimal number system with 16 digits is {0,1,2,3…..9, A(10), B(11),……F(15)}

To convert from binary to hex representation, the bit string id is grouped in blocks of 4-bits which are called as nibbles from the least significant side. Each block is replaced by the corresponding hex digit.

Let’s see an example to get the clarity on hexadecimal and binary number representation.

0011 1110 0101 1011 0001 1101
  3    E    5    B   1    D

We write 0X3E5B1D for a hex constant in C language.

Another example which What iss how to convert decimal to binary and then to hexadecimal is as follows −

7529D = 0000 0000 0000 0000 0001 1101 0110 1001B
      = 0x00001D69 = 0x1D69

Example

Following is the C program which What is how the binary number is converted into its equivalent hexadecimal number by using while loop

 Live Demo

#include <stdio.h>
int main(){
   long int binaryval, hexadecimalval = 0, i = 1, remainder;
   printf("Enter the binary number: ");
   scanf("%ld", &binaryval);
   while (binaryval != 0){
      remainder = binaryval % 10;
      hexadecimalval = hexadecimalval + remainder * i;
      i = i * 2;
      binaryval = binaryval / 10;
   }
   printf("Equivalent hexadecimal value: %lX", hexadecimalval);
   return 0;
}

Output

When the above program is executed, it produces the following result −

Enter the binary number: 11100
Equivalent hexadecimal value: 1C

Updated on: 03-Sep-2021

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements