C Program To Convert Binary To Hexadecimal
In this article, you will learn how to write C programs to convert binary numbers to their hexadecimal equivalents. This conversion is fundamental in computer science, bridging human-readable binary data with more compact hexadecimal representations.
Problem Statement
Converting a binary number to hexadecimal is a common task in programming, especially when dealing with low-level operations, memory addresses, or data representation. Binary numbers, while direct, can be very long and cumbersome for humans to read and write. Hexadecimal offers a more concise representation, where each hexadecimal digit represents four binary digits (bits), making it a convenient shorthand. The challenge is to accurately translate between these bases using C programming.
Example
Consider the binary number 11010110.
- Grouping it into 4-bit segments from right to left:
1101 0110 - Converting each segment to its decimal equivalent:
-
1101(binary) = $1 \cdot 2^3 + 1 \cdot 2^2 + 0 \cdot 2^1 + 1 \cdot 2^0 = 8 + 4 + 0 + 1 = 13$ -
0110(binary) = $0 \cdot 2^3 + 1 \cdot 2^2 + 1 \cdot 2^1 + 0 \cdot 2^0 = 0 + 4 + 2 + 0 = 6$ - Converting decimal values to hexadecimal:
-
13(decimal) =D(hexadecimal) -
6(decimal) =6(hexadecimal) - Combining them:
D6(hexadecimal)
So, 11010110 (binary) converts to D6 (hexadecimal).
Background & Knowledge Prerequisites
To understand the solutions presented, you should have a basic understanding of:
- C Programming Basics: Variables, data types (especially
chararrays for strings,long longfor numbers), loops (for,while), conditional statements (if,else if,else,switch). - Number Systems:
- Binary (Base-2): Uses digits 0 and 1.
- Decimal (Base-10): Uses digits 0-9.
- Hexadecimal (Base-16): Uses digits 0-9 and letters A-F (where A=10, B=11, C=12, D=13, E=14, F=15).
- String Manipulation in C: Working with
chararrays, using functions likestrlen(),strcpy(),strrev(). - Mathematical Operations: Powers, division, modulus.
Use Cases or Case Studies
Binary to hexadecimal conversion is vital in various domains:
- Network Programming: Representing MAC addresses, IP addresses (in some contexts), or network packet data in a more compact form.
- Embedded Systems: Configuring registers, reading sensor data, or debugging memory in microcontrollers where data is often displayed in hexadecimal.
- Security and Cryptography: Hashing algorithms and encryption keys often output or require input in hexadecimal format.
- Web Development (CSS/HTML): Color codes are frequently represented in hexadecimal (e.g.,
#RRGGBB). While the direct input is often decimal or hex, understanding the underlying binary can be useful. - Reverse Engineering and Debugging: Analyzing machine code, memory dumps, or executable files often involves interpreting hexadecimal values which directly correspond to underlying binary instructions.
Solution Approaches
We will explore two common methods for converting binary to hexadecimal in C:
1. Convert Binary to Decimal, then Decimal to Hexadecimal
This approach breaks the problem into two well-understood conversions. First, the binary number is converted to its decimal equivalent. Then, that decimal number is converted into its hexadecimal string representation.
- One-line summary: Convert the binary string to a decimal integer, then convert this decimal integer to a hexadecimal string.
- Code example:
// Binary to Decimal to Hexadecimal Converter
#include <stdio.h>
#include <string.h>
#include <math.h> // For pow function, though direct multiplication is often better for performance
#include <stdlib.h> // For itoa if available, or custom implementation
// Function to convert binary string to decimal long long
long long binaryToDecimal(const char *binaryString) {
long long decimal = 0;
int power = 0;
int length = strlen(binaryString);
for (int i = length - 1; i >= 0; i--) {
if (binaryString[i] == '1') {
decimal += (long long)pow(2, power);
} else if (binaryString[i] != '0') {
printf("Error: Invalid binary digit '%c'\\n", binaryString[i]);
return -1; // Indicate an error
}
power++;
}
return decimal;
}
// Function to convert decimal long long to hexadecimal string
void decimalToHexadecimal(long long decimalNum, char *hexadecimalString) {
if (decimalNum == 0) {
strcpy(hexadecimalString, "0");
return;
}
char hexChars[] = "0123456789ABCDEF";
int i = 0;
char tempHex[100]; // Temporary buffer for reverse order
while (decimalNum > 0) {
tempHex[i++] = hexChars[decimalNum % 16];
decimalNum /= 16;
}
tempHex[i] = '\\0';
// Reverse the temporary string to get the correct hexadecimal order
int start = 0;
int end = i - 1;
while (start < end) {
char temp = tempHex[start];
tempHex[start] = tempHex[end];
tempHex[end] = temp;
start++;
end--;
}
strcpy(hexadecimalString, tempHex);
}
int main() {
char binaryInput[100];
char hexadecimalOutput[100];
printf("Enter a binary number: ");
scanf("%s", binaryInput);
long long decimalResult = binaryToDecimal(binaryInput);
if (decimalResult != -1) { // Check for valid binary input
decimalToHexadecimal(decimalResult, hexadecimalOutput);
printf("Binary: %s\\n", binaryInput);
printf("Decimal: %lld\\n", decimalResult);
printf("Hexadecimal: %s\\n", hexadecimalOutput);
}
return 0;
}
- Sample output:
Enter a binary number: 11010110
Binary: 11010110
Decimal: 214
Hexadecimal: D6
- Stepwise explanation:
binaryToDecimal(const char *binaryString):
- Initializes
decimalto 0 andpowerto 0. - It iterates through the
binaryStringfrom right to left (least significant bit to most significant bit). - If a
1is encountered,pow(2, power)is added todecimal. - The
poweris incremented for the next bit. - Returns the accumulated
decimalvalue.
decimalToHexadecimal(long long decimalNum, char *hexadecimalString):
- Handles the special case where
decimalNumis 0, returning "0". - Uses a
hexCharsarray to map remainders (0-15) to their respective hexadecimal characters. - It repeatedly performs
decimalNum % 16to get the remainder anddecimalNum /= 16to update the number. - The remainders (converted to hex characters) are stored in a temporary buffer
tempHexin reverse order. - Finally, the
tempHexstring is reversed and copied intohexadecimalStringto give the correct hexadecimal representation.
main()function:
- Prompts the user to enter a binary number.
- Calls
binaryToDecimalto get the decimal equivalent. - If the binary input was valid, it calls
decimalToHexadecimalto convert the decimal to hexadecimal. - Prints all three representations.
2. Direct Binary to Hexadecimal (Grouping 4 Bits)
This method directly converts groups of four binary digits (bits) into one hexadecimal digit, which is often more efficient as it avoids the intermediate decimal conversion for large numbers.
- One-line summary: Pad the binary string to a length divisible by 4, then convert each 4-bit segment directly to its corresponding hexadecimal character.
- Code example:
// Direct Binary to Hexadecimal Converter
#include <stdio.h>
#include <string.h>
#include <stdlib.h> // For malloc, free
// Function to get decimal value of a 4-bit binary string
int getDecimalValue(const char *fourBits) {
int val = 0;
if (fourBits[0] == '1') val += 8;
if (fourBits[1] == '1') val += 4;
if (fourBits[2] == '1') val += 2;
if (fourBits[3] == '1') val += 1;
return val;
}
// Function to convert binary string directly to hexadecimal string
void binaryToHexadecimalDirect(const char *binaryInput, char *hexadecimalOutput) {
char hexChars[] = "0123456789ABCDEF";
int len = strlen(binaryInput);
int outputIndex = 0;
int padding = 0;
// Calculate padding needed to make length a multiple of 4
if (len % 4 != 0) {
padding = 4 - (len % 4);
}
char *paddedBinary = (char *)malloc(len + padding + 1);
if (paddedBinary == NULL) {
strcpy(hexadecimalOutput, "ERROR");
return;
}
// Add leading zeros for padding
for (int i = 0; i < padding; i++) {
paddedBinary[i] = '0';
}
strcpy(paddedBinary + padding, binaryInput); // Copy original binary after padding
paddedBinary[len + padding] = '\\0';
// Process in 4-bit chunks
for (int i = 0; i < len + padding; i += 4) {
char fourBits[5];
strncpy(fourBits, paddedBinary + i, 4);
fourBits[4] = '\\0'; // Null-terminate the 4-bit string
int decimalVal = getDecimalValue(fourBits);
hexadecimalOutput[outputIndex++] = hexChars[decimalVal];
}
hexadecimalOutput[outputIndex] = '\\0'; // Null-terminate the final hex string
free(paddedBinary); // Free dynamically allocated memory
}
int main() {
char binaryInput[100];
char hexadecimalOutput[100];
printf("Enter a binary number: ");
scanf("%s", binaryInput);
binaryToHexadecimalDirect(binaryInput, hexadecimalOutput);
printf("Binary: %s\\n", binaryInput);
printf("Hexadecimal: %s\\n", hexadecimalOutput);
return 0;
}
- Sample output:
Enter a binary number: 11010110
Binary: 11010110
Hexadecimal: D6
Enter a binary number: 101011
Binary: 101011
Hexadecimal: 2B
- Stepwise explanation:
getDecimalValue(const char *fourBits):
- This helper function takes a 4-character binary string (e.g., "1101").
- It directly calculates its decimal equivalent by checking each bit position and adding the corresponding power of 2 (8, 4, 2, 1).
- Returns the decimal value (0-15).
binaryToHexadecimalDirect(const char *binaryInput, char *hexadecimalOutput):
- Calculates
paddingrequired to make thebinaryInputlength a multiple of 4. - Dynamically allocates memory for
paddedBinaryto hold the original string with leading zeros. - Copies the padding zeros and then the original
binaryInputintopaddedBinary. - It then iterates through
paddedBinaryin chunks of 4 characters. - For each 4-character chunk:
- It extracts the 4-bit string using
strncpy. - Calls
getDecimalValueto find its decimal value (0-15). - Uses the
hexCharsarray to map this decimal value to its hexadecimal character (e.g., 10 maps to 'A', 15 maps to 'F'). - Appends this hexadecimal character to
hexadecimalOutput. - Finally, it null-terminates
hexadecimalOutputand frees the dynamically allocated memory forpaddedBinary.
main()function:
- Prompts the user for a binary number.
- Calls
binaryToHexadecimalDirectto perform the conversion. - Prints the original binary and the resulting hexadecimal string.
Conclusion
Converting binary to hexadecimal is a fundamental skill in computing, simplifying complex binary strings into more manageable forms. We explored two primary methods in C: the indirect approach of converting through decimal and the more direct approach of grouping 4 bits. While the binary-to-decimal-to-hexadecimal method is conceptually straightforward, the direct 4-bit grouping method is often more efficient for large binary strings as it avoids intermediate numerical representation that might exceed standard integer limits.
Summary
- Binary numbers are long and verbose.
- Hexadecimal numbers provide a compact representation where each digit corresponds to four binary bits.
- Method 1 (Binary -> Decimal -> Hexadecimal):
- Involves converting the binary string to its decimal equivalent.
- Then, converting the decimal number to a hexadecimal string by repeatedly taking the modulus and division by 16.
- Method 2 (Direct 4-bit Grouping):
- Pads the binary string with leading zeros to ensure its length is a multiple of 4.
- Converts each 4-bit segment directly to its corresponding hexadecimal digit.
- This method is generally more efficient for larger binary inputs.
- Both methods effectively achieve the conversion, with the choice often depending on clarity, performance requirements, and the scale of the binary numbers being processed.