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