C Online Compiler
Example: Hexadecimal to Binary Converter with Lookup Array in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Hexadecimal to Binary Converter with Lookup Array #include <stdio.h> #include <string.h> // Required for strlen() #include <ctype.h> // Required for toupper() // Lookup array for 4-bit binary equivalents of hex digits (0-F) const char* hex_to_bin_map[] = { "0000", "0001", "0010", "0011", // 0, 1, 2, 3 "0100", "0101", "0110", "0111", // 4, 5, 6, 7 "1000", "1001", "1010", "1011", // 8, 9, A, B "1100", "1101", "1110", "1111" // C, D, E, F }; // Function to get the integer value of a hexadecimal character int get_hex_value(char c) { if (c >= '0' && c <= '9') { return c - '0'; } else if (c >= 'A' && c <= 'F') { // Handle uppercase A-F return c - 'A' + 10; } else if (c >= 'a' && c <= 'f') { // Handle lowercase a-f return c - 'a' + 10; } else { return -1; // Invalid hex character } } int main() { char hexNum[20]; int i = 0; // Step 1: Prompt user for input printf("Enter a hexadecimal number: "); scanf("%s", hexNum); printf("Binary equivalent: "); // Step 2: Iterate through each character of the hexadecimal string while (hexNum[i] != '\0') { int val = get_hex_value(hexNum[i]); // Get integer value of current hex digit if (val != -1) { // Check if it's a valid hex digit printf("%s", hex_to_bin_map[val]); // Print corresponding binary string from lookup map } else { printf("\nError: Invalid hexadecimal digit '%c' found.\n", hexNum[i]); return 1; // Indicate error and exit } i++; } printf("\n"); return 0; }
Output
Clear
ADVERTISEMENTS