C Program for Conversion Between Binary and Hexadecimal
Binary to Hexadecimal:
A binary number is represented by 0s and 1s, while a hexadecimal number is represented by digits from 0 to 9 and letters from A to F. To convert binary to hexadecimal, we can split the binary number into groups of 4 bits (starting from the right). Each 4-bit group corresponds to a single hexadecimal digit.
Example:
Binary: 11010111 → Split as 1101 and 0111 → Hexadecimal: D7
Hexadecimal to Binary:
To convert hexadecimal to binary, we replace each hexadecimal digit with its 4-bit binary equivalent.
Example:
Hexadecimal: D7 → D becomes 1101 and 7 becomes 0111 → Binary: 11010111
Code
#include <stdio.h>
#include <string.h>
#include <math.h>
// Function to convert binary to hexadecimal
void binaryToHexadecimal(char binary[]) {
int len = strlen(binary);
int decimal = 0;
// Convert binary to decimal
for (int i = 0; i < len; i++) {
if (binary[len - i - 1] == '1') {
decimal += pow(2, i);
}
}
// Convert decimal to hexadecimal
char hex[20];
sprintf(hex, "%X", decimal);
printf("Hexadecimal: %s\n", hex);
}
// Function to convert hexadecimal to binary
void hexadecimalToBinary(char hex[]) {
int decimal = 0;
// Convert hexadecimal to decimal
sscanf(hex, "%x", &decimal);
// Convert decimal to binary
char binary[50] = "";
int index = 0;
while (decimal > 0) {
binary[index++] = (decimal % 2) ? '1' : '0';
decimal /= 2;
}
binary[index] = '\0';
// Reverse the binary string
for (int i = 0; i < index / 2; i++) {
char temp = binary[i];
binary[i] = binary[index - i - 1];
binary[index - i - 1] = temp;
}
printf("Binary: %s\n", binary);
}
int main() {
char binary[50], hex[20];
printf("Enter a binary number: ");
scanf("%s", binary);
binaryToHexadecimal(binary);
printf("Enter a hexadecimal number: ");
scanf("%s", hex);
hexadecimalToBinary(hex);
return 0;
}
Output
Enter a binary number: 11010111
Hexadecimal: D7
Enter a hexadecimal number: D7
Binary: 11010111
Explanation of Code
binaryToHexadecimal Function:
This function takes a binary string, converts it to decimal, and then to hexadecimal. First, it calculates the decimal value from the binary string using powers of 2. Then, it converts the decimal to hexadecimal using sprintf
.
hexadecimalToBinary Function:
This function takes a hexadecimal string, converts it to decimal, and then to binary. sscanf
reads the hexadecimal input and stores it as an integer (decimal). We then convert the decimal to binary by dividing by 2 iteratively and storing the remainder. The binary string is reversed to display it in the correct order.
This program provides an efficient way to handle binary and hexadecimal conversions using C.