Convert Binary to Hex Using C Language



Binary numbers are represented in 1's and 0's. It can also be referred to as a rational number with a finite representation in the system. This is a quotient of an integer by a power of two.

Hexadecimal number system with 16 digits is {0,1,2,3?..9, A(10), B(11),??F(15)}. In base 16 transfer encoding, each byte of plain text is divided into two 4-bit values, which are represented by two hexadecimal digits.

Converting Binary to Hex using C

To convert from binary to hexadecimal representation, the bit string is grouped into 4-bit blocks, called nibbles, starting from the least significant side. Each block is then replaced by the corresponding hexadecimal digit. Let's see an example to get clarity on hexadecimal and binary number representation.

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

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

Here is another example that demonstrates how to convert a decimal number to binary and then to hexadecimal ?

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

Example

Here is a C program that demonstrates how to convert a binary number into its equivalent hexadecimal number using a while loop ?

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

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

Enter the binary number: 11100
Equivalent hexadecimal value: 1C
Updated on: 2024-12-09T16:44:29+05:30

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements