Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to convert binary to Hex by using C language?
Binary numbers are represented using only 1's and 0's. Hexadecimal numbers use 16 digits: {0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F} where A=10, B=11, C=12, D=13, E=14, F=15.
Syntax
// Convert binary string to decimal first, then to hex int binaryToDecimal(long binary); void decimalToHex(int decimal, char hex[]);
Converting Binary to Hex Process
To convert binary to hexadecimal, group the binary digits into 4-bit blocks (nibbles) from right to left. Each 4-bit group represents one hexadecimal digit −
Method 1: Using String Input
This approach takes binary as a string and converts it directly to hexadecimal −
#include <stdio.h>
#include <string.h>
#include <math.h>
int binaryToDecimal(char binary[]) {
int decimal = 0;
int base = 1;
int len = strlen(binary);
for (int i = len - 1; i >= 0; i--) {
if (binary[i] == '1') {
decimal += base;
}
base *= 2;
}
return decimal;
}
int main() {
char binary[32];
printf("Enter binary number: ");
scanf("%s", binary);
int decimal = binaryToDecimal(binary);
printf("Binary: %s<br>", binary);
printf("Decimal: %d<br>", decimal);
printf("Hexadecimal: %X<br>", decimal);
return 0;
}
Enter binary number: 11100101 Binary: 11100101 Decimal: 229 Hexadecimal: E5
Method 2: Using Integer Input
This method takes binary as an integer and converts it step by step −
#include <stdio.h>
int main() {
long int binaryval, decimal = 0, base = 1, remainder;
printf("Enter the binary number: ");
scanf("%ld", &binaryval);
long int temp = binaryval;
// Convert binary to decimal
while (binaryval != 0) {
remainder = binaryval % 10;
decimal = decimal + remainder * base;
base = base * 2;
binaryval = binaryval / 10;
}
printf("Binary: %ld<br>", temp);
printf("Decimal: %ld<br>", decimal);
printf("Hexadecimal: %lX<br>", decimal);
return 0;
}
Enter the binary number: 11100 Binary: 11100 Decimal: 28 Hexadecimal: 1C
Comparison Table
| Method | Input Type | Pros | Cons |
|---|---|---|---|
| String Input | char array | Handles longer binary numbers | More complex string handling |
| Integer Input | long int | Simple arithmetic operations | Limited to long int range |
Key Points
- Each group of 4 binary digits equals one hexadecimal digit
- Conversion process: Binary ? Decimal ? Hexadecimal
- Use
%Xformat specifier for uppercase hex output - Use
%xformat specifier for lowercase hex output
Conclusion
Converting binary to hexadecimal in C involves first converting to decimal, then using printf with %X format. Both string and integer methods work effectively depending on your input requirements.
Advertisements
