Home > Backend Development > C++ > How to convert binary to hexadecimal using C language?

How to convert binary to hexadecimal using C language?

PHPz
Release: 2023-09-01 18:57:06
forward
1923 people have browsed it

How to convert binary to hexadecimal using C language?

Binary numbers are represented by 1 and 0.

The 16-digit hexadecimal number system is {0,1,2,3…..9, A(10), B(11),… …F(15)}

To convert from binary to hexadecimal representation, the bit string id is grouped into 4-bit blocks, called nibbles starting from the least significant side. Each block is replaced with the corresponding hexadecimal number.

Let us see an example to get a clear understanding of hexadecimal and binary number representation.

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

We write hexadecimal constants as 0X3E5B1D in C language.

Another example on how to convert decimal to binary and then to hexadecimal is as follows -

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

Example

The following is the C program,How Use a while loop to convert a binary number to an equivalent hexadecimal number -

Live demonstration

#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;
}
Copy after login

Output

When the above program is executed, it will be generated The following results-

Enter the binary number: 11100
Equivalent hexadecimal value: 1C
Copy after login

The above is the detailed content of How to convert binary to hexadecimal using C language?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template