C Online Compiler
Example: Direct Binary to Hexadecimal Converter in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// 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; }
Output
Clear
ADVERTISEMENTS