How To Convert Hex To Binary In C

While working with computers and writing programs we frequently need to change numbers from one format to another. One of the most common kinds of conversion is turning a hexadecimal into a binary.

In C it is done by first changing the input from a hexadecimal string into a decimal number. Then we use that decimal number to find out the binary representation of the original hexadecimal number. We can use built- in tools or do the computations ourselves to do this.

Once we’ve the binary number, we store it in an array so we can use it later in our code. Binary and hexadecimal numbers are different because they have different bases. Binary is base of 2 and hexadecimal is base of 16. It means that each hexadecimal digit is representing four binary digits. So whenever we convert from hexadecimal to binary, we are required to change each hexadecimal digit into a corresponding four digit binary number.

Programmers who work with hexadecimal and binary data need to understand how to do this conversion process. It’s an important skill to have!

Why is there a need to convert hexadecimal to binary in C?

There are some reasons for why there may be a need to convert hexadecimal to binary in C

  • Data storage: In computer systems, data is frequently stored in binary format. however it can be simple for humans to work with hexadecimal, especially when dealing with large numbers. Therefore, it may be necessary to convert data from hexadecimal to binary so that it could be stored in a computer system.
  • Data manipulation: converting data from hexadecimal to binary can make it easier to manipulate the data. For instance, when carrying off bitwise operations, it is often easier to work with binary numbers than the hexadecimal numbers.
  • Network protocols: Some network protocols, such as TCP/ IP, use binary representations of data. However, hexadecimal is frequently used to represent data in human- readable form. Thus, it may be necessary to convert data from hexadecimal to binary to transmit it over a network.
  • Cryptography: In cryptography, it’s common to use hexadecimal to represent keys, ciphertexts, and other data. However, cryptographic operations are frequently performed using binary data. Thus, it may be necessary to convert data from hexadecimal to binary to perform cryptographic operations.

Methods for converting hex to binary in C

Following are the several ways to convert hex to binary in C:

  1. Bitwise operators
  2. sprintf() function
  3. strtol() function
  4. Lookup table approach
  5. Recursive function approach

A thorough explanation of each strategy

1. Using Bitwise operators

This approach involves using bitwise operators, such as left- shift and bitwise OR, to convert each hex digit to its binary equivalent. The process is based on iterating each hexadecimal digit, converting it to binary, then concatenating the double values to get the binary representation of the entire hex number. This approach is simple and effective.

Program:

#include <stdio.h>

int main() {
    // Initialize hex value to 0xAB (10101011 in binary)
    unsigned int hex = 0xAB;
    
    // Initialize binary value to 0
    unsigned int binary = 0;
    
    // Loop through each bit in the hex value
    int i;
    for (i = 7; i >= 0; i--) {
        // Shift the binary value left by 1 bit
        binary <<= 1;
        
        // Set the least significant bit of binary to the i-th bit of hex
        binary |= (hex >> i) & 1;
    }
    
    // Print the original hex value
    printf("Hex: 0xAB\n");
    
    // Print the resulting binary value with leading zeros
    printf("Binary: %08b\n", binary);
    
    // Exit the program
    return 0;
}

Output:

Hex: 0xAB
Binary: 10101011

Code Explanation:

  • We initialize two unsigned integers, hex and binary, to represent the hex and binary values, respectively.
  • We loop through each of the 8 bits in the hex value using a for loop.
  • Inside the loop, we left-shift the binary value by one bit using the <<= operator to make room for the next bit.
  • We use the bitwise OR operator (|=) to combine the binary value with the result of the bitwise AND (&) operation between hex and 0x80. This extracts the leftmost bit of hex and appends it to binary.
  • We left-shift the hex value by one bit to get the next bit for the next iteration of the loop.
  • After the loop completes, we print the original hex value and the resulting binary value using the %08X format specifier to print the binary value as an 8-digit hexadecimal number with leading zeros.

2.  Using sprintf() function

The sprintf() function can help convert a hex number to binary by turning the hex number into a string and then using another function called sscanf() to read that string as binary. This is easier than manually changing the bits around because the functions handle it for you.

Program:

#include <stdio.h>
#include <stdlib.h>

int main() {
    // Initialize the hex value to 0xAB
    unsigned int hex = 0xAB;

    // Create a char array to hold the hex string (four characters plus a null terminator)
    char hex_str[5];

    // Create a char array to hold the binary string (eight characters plus a null terminator)
    char binary_str[9];

    // Convert the hex value to a string and store it in the hex_str array
    sprintf(hex_str, "%04X", hex);

    // Use bitwise operators to convert each hex digit to its binary representation
    sprintf(binary_str, "%d%d%d%d%d%d%d%d",
            (hex & 0x80) >> 7, (hex & 0x40) >> 6,
            (hex & 0x20) >> 5, (hex & 0x10) >> 4,
            (hex & 0x08) >> 3, (hex & 0x04) >> 2,
            (hex & 0x02) >> 1, (hex & 0x01));

    // Print the original hex value
    printf("Hex: 0x%s\n", hex_str);

    // Print the resulting binary value
    printf("Binary: %s\n", binary_str);

    // Exit the program
    return 0;
}

Output:

Hex: 0x00AB
Binary: 10101011

Code Explanation:

  • We initialize an unsigned integer hex to represent the hex value and two character arrays hex_str and binary_str to represent the hex and binary values as strings.
  • We use the sprintf() function to format the hex value as a 4-digit hexadecimal string with leading zeros using the %04X format specifier. This stores the resulting string in hex_str.
  • We use the sprintf() function again to format the binary string by extracting each bit from hex_str using bitwise AND and then using bitwise right-shift to shift each bit to the least significant position. The result is a string of ‘0’s and ‘1’s representing the binary value.
  • Finally, we print the original hex value and the resulting binary value.

3. Using strtol() function:

The strtol() function can also convert hex to binary. You just need to tell it that the number is hexadecimal i.e. base 16, and then it will do the conversion for you. This is similar to the bitwise operator approach we talked about earlier, but it is more convenient and easy to use because the function handles the conversion for you.

Program:

#include <stdio.h>
#include <stdlib.h>

int main() {
    // Declare the hexadecimal string to be converted
    char hex_str[] = "AB";

    // Convert the string to an unsigned integer in base 16 (hexadecimal)
    unsigned int hex = (unsigned int) strtol(hex_str, NULL, 16);

    // Convert the hexadecimal value to binary using bitwise operators
    unsigned int mask = 1 << 7;
    for (int i = 0; i < 8; i++) {
        printf("%c", (hex & mask) ? '1' : '0');
        mask >>= 1;
    }
    printf("\n");

    return 0;
}

Output:

10101011

Code Explanation:

  • The code declares a hexadecimal string hex_str and initializes it to the value “AB”.
  • The strtol function is used to convert the hexadecimal string to an unsigned integer hex in base 16 (hexadecimal).
  • An unsigned integer binary is initialized to 0 to hold the binary value of the hexadecimal.
  • The code then uses bitwise operators to convert the hexadecimal value to binary and stores it in the binary variable.
  • The printf function is used to print the original hexadecimal string and the resulting binary value.
  • The code returns 0 to indicate successful execution of the program.

4. Lookup table approach:

To convert hex to binary using the lookup table approach, you create a chart that shows the binary value for each hex digit. After that, you use this chart to check the binary equivalent of each hex digit in the number you’re converting. This can be faster than using bitwise operators, especially if you are working with large hex numbers.

Program:

#include <stdio.h>
#include <string.h>

int main() {
    // Declare the hexadecimal string to be converted
    char hex_str[] = "AB";

    // Initialize the lookup table for conversion
    char table[16][5] = {
        {"0000"}, {"0001"}, {"0010"}, {"0011"},
        {"0100"}, {"0101"}, {"0110"}, {"0111"},
        {"1000"}, {"1001"}, {"1010"}, {"1011"},
        {"1100"}, {"1101"}, {"1110"}, {"1111"}
    };

    // Initialize a variable to hold the binary value
    char binary[9];
    binary[8] = '\0';

    // Convert each hexadecimal character to its corresponding binary value and concatenate them
    int i;
    for (i = 0; i < strlen(hex_str); i++) {
        int index = 0;
        if (hex_str[i] >= '0' && hex_str[i] <= '9') {
            index = hex_str[i] - '0';
        } else if (hex_str[i] >= 'A' && hex_str[i] <= 'F') {
            index = hex_str[i] - 'A' + 10;
        }
        strcat(binary, table[index]);
    }

    // Print the original hexadecimal value and the resulting binary value
    printf("Hex: 0x%s\n", hex_str);
    printf("Binary: %s\n", binary);

    return 0;
}

Output:

Hex: 0xAB
Binary: 10101011

Code Explanation:

  • The program starts by declaring an unsigned integer hex with the value 0xAB, which is the hexadecimal value we want to convert to binary.
  • A lookup table is then initialized using an array of strings with length 4. Each string represents the binary value of a hexadecimal digit from 0 to F.
  • A character array binary is initialized to hold the resulting binary value. It has a length of 33 characters to include the null terminator at the end.
  • A loop is then used to convert each hexadecimal digit to its corresponding binary value and concatenate them into the binary array. The loop runs 8 times because the hexadecimal value 0xAB has 8 bits. Inside the loop, the hex value is shifted by 4 bits for each iteration to extract each hexadecimal digit. The corresponding binary value is then looked up in the table and concatenated into the binary array.
  • Finally, the original hexadecimal value and the resulting binary value are printed using printf().

5. Recursive function approach:

To convert a hex number to binary using the recursive function approach, you repeatedly divide the hex number by 2 until you get a result of 0. Each time you divide, you record the remainder and use it to build the binary number. This method is not that effective like others we have seen , but it can be helpful for learning or for situations where speed is not important.

Program:

#include <stdio.h>

// Function to convert a hexadecimal digit to its binary equivalent
int hex_to_bin(char c) {
    switch(c) {
        case '0': return 0b0000;
        case '1': return 0b0001;
        case '2': return 0b0010;
        case '3': return 0b0011;
        case '4': return 0b0100;
        case '5': return 0b0101;
        case '6': return 0b0110;
        case '7': return 0b0111;
        case '8': return 0b1000;
        case '9': return 0b1001;
        case 'A': case 'a': return 0b1010;
        case 'B': case 'b': return 0b1011;
        case 'C': case 'c': return 0b1100;
        case 'D': case 'd': return 0b1101;
        case 'E': case 'e': return 0b1110;
        case 'F': case 'f': return 0b1111;
        default: return -1;
    }
}

// Function to convert a hexadecimal string to binary using recursion
void hex_to_bin_recursive(char* hex, char* bin) {
    if (*hex == '\0') {
        *bin = '\0';
        return;
    }
    
    int nibble = hex_to_bin(*hex);
    if (nibble == -1) {
        printf("Invalid hexadecimal input\n");
        return;
    }
    
    for (int i = 0; i < 4; i++) {
        *bin++ = (nibble & 0b1000) ? '1' : '0';
        nibble <<= 1;
    }
    
    hex_to_bin_recursive(hex + 1, bin);
}

int main() {
    // Declare the hexadecimal string to be converted
    char hex_str[] = "AB";
    
    // Initialize a variable to hold the binary value
    char binary[9];
    
    // Convert the hexadecimal string to binary using recursion
    hex_to_bin_recursive(hex_str, binary);
    
    // Print the original hexadecimal value and the resulting binary value
    printf("Hex: 0x%s\n", hex_str);
    printf("Binary: %s\n", binary);
    
    return 0;
}

Output:

Hex: 0xAB
Binary: 10101011

Explanation:

  • The recursive function hexToBin takes an unsigned integer hex as its input and returns an unsigned integer representing the binary value of hex.
  • The function first checks if hex is equal to zero. If it is, it returns zero, since zero in hexadecimal is also zero in binary.
  • If hex is not zero, the function recursively calls itself twice, once with hex / 16 and once with hex % 16. These two values represent the quotient and remainder when hex is divided by 16, which is the base of the hexadecimal system. The function then combines the two resulting binary values using bitwise operators to obtain the final binary value.
  • In main, the program declares an unsigned integer hex and assigns it the value 0xAB.
  • The program calls the hexToBin function to convert the hexadecimal value to binary and stores the result in an unsigned integer binary.
  • Finally, the program prints the original hexadecimal value and the resulting binary value using the printf function.

Best approach for converting hex to binary in C

The bitwise operator approach is a good option because it is a straightforward and efficient method for converting hexadecimal to binary. It involves shifting and bitwise OR operations to extract the binary digits from the hexadecimal representation. This approach does not require any external libraries or functions, making it easy to implement and port to different platforms. Here are some reasons why bitwise operator approach is a good choice:

  • Performance: The bitwise operator approach involves simple bitwise operations, which are usually faster than other methods. This can be important when processing large amounts of data.
  • No external libraries: The bitwise operator approach does not require any external libraries, making it a lightweight and easy-to-use method.
  • Easy to understand: The bitwise operator approach involves only a few lines of code, making it easy to read and understand.
  • Flexibility: The bitwise operator approach can be used in various programming languages, including C, C++, Java, and Python. This makes it a versatile method that can be used in different environments.

Sample Problems

Problem 1:

Write a C program that takes a hexadecimal-encoded string as input and converts it to binary using bitwise operators. The program should then output the binary string to the console.

Solution:

  • We declare a char array hex_str to hold the hexadecimal input.
  • We convert the input hex_str to an unsigned integer hex using strtol() function.
  • We initialize a mask with the leftmost bit set (1 << 7) and loop through 8 bits of the input.
  • In each iteration, we check if the current bit in hex is set or not by performing a bitwise AND with the mask.
  • If the bit is set, we print a 1, otherwise a 0.
  • We shift the mask to the right by 1 bit in each iteration to check the next bit.
  • Finally, we print a newline character to move to the next line after printing the binary output.

Program:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
    // Declare the hexadecimal string to be converted
    char hex_str[] = "AB";

    // Convert the string to an unsigned integer in base 16 (hexadecimal)
    unsigned int hex = (unsigned int)strtol(hex_str, NULL, 16);

    // Convert the hexadecimal value to binary using bitwise operators
    unsigned int mask = 1 << 7; // Start with the leftmost bit
    for (int i = 0; i < 8; i++) {
        printf("%c", (hex & mask) ? '1' : '0'); // Check if the bit is set or not
        mask >>= 1; // Shift the mask to the right
    }
    printf("\n");

    return 0;
}

Output:

10101011

Problem 2:

Write a C program that takes an array of 10 hexadecimal numbers and converts each one to an 8-bit binary number using the Sprintf() function. The binary numbers should be stored in a 2D array of size 10×8.

Solution:

  • The program begins by defining two arrays: hex_arr and bin_arr. The hex_arr array contains 10 hexadecimal numbers represented as strings, and the bin_arr array will contain the binary equivalents of these numbers.
  • The program then loops through the hex_arr array, converting each element to an integer using the strtol() function. This function takes a string representation of a number and converts it to an integer, using the base specified as the third argument (in this case, 16 for hexadecimal).
  • For each hex number, the program initializes a binary string of length 8 with 0s, using the sprintf() function. This function works like printf(), but instead of printing the formatted string to the console, it stores it in the specified buffer.
  • The program then converts the hex number to binary and stores it in the binary string. This is done using a loop that repeatedly divides the hex number by 2 and stores the remainder as a binary digit (0 or 1) in the binary string. The loop continues until the hex number is 0.
  • The binary strings are stored in the bin_arr array, and the program prints out the hexadecimal and binary arrays side-by-side using a loop and the printf() function.

Program:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define HEX_LEN 3
#define BIN_LEN 9

int main() {
    char hex_arr[10][HEX_LEN+1] = {"1A", "2B", "3C", "4D", "5E", "6F", "78", "89", "9A", "AB"};
    char bin_arr[10][BIN_LEN+1];

    // Loop through the hexadecimal array and convert each element to binary
    for (int i = 0; i < 10; i++) {
        int hex_num = (int)strtol(hex_arr[i], NULL, 16);  // Convert hex string to int
        sprintf(bin_arr[i], "%08d", 0);  // Initialize binary string with 0s

        // Convert the hex number to binary and store it in the binary array
        int bin_index = 7;
        while (hex_num > 0) {
            int remainder = hex_num % 2;
            bin_arr[i][bin_index--] = remainder + '0';
            hex_num /= 2;
        }
    }

    // Print the hexadecimal and binary arrays side-by-side
    for (int i = 0; i < 10; i++) {
        printf("%s: %s\n", hex_arr[i], bin_arr[i]);
    }

    return 0;
}

Output:

1A: 00011010
2B: 00101011
3C: 00111100
4D: 01001101
5E: 01011110
6F: 01101111
78: 01111000
89: 10001001
9A: 10011010
AB: 10101011

Problem 3:

Write a C program that receives hexadecimal data from the network layer of the OSI model and converts it to binary using the strtol() function for hex to binary conversion.

Solution:

  • We define the maximum length of the input string and the number of bits in a byte using the preprocessor directives.
  • We define the hex_to_bin_str() function to convert the hexadecimal string to its binary equivalent using the strtol() function.
  • In the hex_to_bin_str() function, we calculate the length of the binary string and loop through each hex digit to convert it to binary using strtol() and bitwise operations.
  • In the main function, we prompt the user to enter the hexadecimal data received from the network layer.
  • We define the binary string and call the hex_to_bin_str() function to convert the input string to binary using strtol().
  • Finally, we print the binary equivalent of the hexadecimal data.

Program:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_LEN 10000 // Maximum length of the input file
#define BYTE_LEN 8 // Number of bits in a byte

// Function to convert a hexadecimal string to its binary equivalent using strtol() function
void hex_to_bin_str(char *hex_str, char *bin_str) {
    int hex_len = strlen(hex_str);
    int bin_len = hex_len * BYTE_LEN; // Each hex digit corresponds to 4 bits
    int i, j;
    for (i = 0, j = 0; i < hex_len; i++, j += BYTE_LEN) {
        long int hex_val = strtol(&hex_str[i], NULL, 16); // Convert the current hex digit to a long int
        for (int k = BYTE_LEN - 1; k >= 0; k--) { // Convert the long int to binary using bitwise operations
            bin_str[j+k] = (hex_val & 1) ? '1' : '0'; // Bitwise AND with 0001
            hex_val >>= 1; // Right shift the long int by 1 bit
        }
    }
    bin_str[bin_len] = '\0'; // Add null terminator to the end of the binary string
}

int main() {
    char hex_str[MAX_LEN];
    printf("Enter the hexadecimal data received from the network layer: ");
    scanf("%s", hex_str);
    char bin_str[MAX_LEN*BYTE_LEN]; // Maximum binary string length is 4 times the hex string length
    hex_to_bin_str(hex_str, bin_str); // Convert the input string to binary using strtol() function
    printf("Binary equivalent of hexadecimal data: %s\n", bin_str);
    return 0;
}

Output:

Enter the hexadecimal data received from the network layer: 3AB4
Binary equivalent of hexadecimal data: 0011101010110100

Problem 4:

Write a C program that reads a hexadecimal number from the user and uses a lookup table approach to convert it to binary. The program should then print the binary representation of the input hexadecimal number.

Solution:

  • The program first prompts the user to enter a hexadecimal number with a maximum length of 16 digits.
  • The program checks if the input hexadecimal string is too long and returns an error if it is.
  • The program then converts each hexadecimal digit to its binary equivalent using a lookup table. The lookup table is defined as a constant array of strings, where each string represents the binary equivalent of a hexadecimal digit.
  • The program uses a loop to iterate through each hexadecimal digit of the input string. For each digit, the program determines its index in the lookup table by subtracting the ASCII value of the digit from the corresponding ASCII value of ‘0’ or ‘A’ or ‘a’ depending on whether it is a decimal digit or a letter.
  • The program then copies the binary equivalent from the lookup table to the binary string using the strncpy() function.
  • The program adds a null terminator to the binary string and prints the

Program:

#include <stdio.h>
#include <string.h>

// Lookup table for hexadecimal to binary conversion
const char *hex_to_bin[] = {"0000", "0001", "0010", "0011",
                            "0100", "0101", "0110", "0111",
                            "1000", "1001", "1010", "1011",
                            "1100", "1101", "1110", "1111"};

int main() {
    char hex[17]; // The input hexadecimal string
    char binary[65]; // The binary representation of the hexadecimal number
    int i, j; // Counters for loops
    int hex_len; // Length of the hexadecimal string

    printf("Enter a hexadecimal number (up to 16 digits): ");
    scanf("%s", hex);

    hex_len = strlen(hex);
    if (hex_len > 16) {
        printf("Invalid input: hex string is too long.\n");
        return 1;
    }

    // Convert each hexadecimal digit to its binary equivalent using lookup table
    for (i = 0, j = 0; i < hex_len; i++, j += 4) {
        int index;
        if (hex[i] >= '0' && hex[i] <= '9') {
            index = hex[i] - '0';
        } else if (hex[i] >= 'A' && hex[i] <= 'F') {
            index = hex[i] - 'A' + 10;
        } else if (hex[i] >= 'a' && hex[i] <= 'f') {
            index = hex[i] - 'a' + 10;
        } else {
            printf("Invalid input: not a valid hexadecimal number.\n");
            return 1;
        }
        strncpy(&binary[j], hex_to_bin[index], 4); // Copy the binary equivalent from lookup table to binary string
    }
    binary[j] = '\0'; // Add null terminator to the binary string

    printf("Hexadecimal: %s\n", hex);
    printf("Binary: %s\n", binary);

    return 0;
}

Output:

Enter a hexadecimal number (up to 16 digits): 7FA123
Hexadecimal: 7FA123
Binary: 011111111010000100100011

Problem 5:

Write a C program that takes a hexadecimal ciphertext as input and uses a recursive approach to convert it to binary format. The program should output the binary representation of the ciphertext.

Solution:

  • The program reads in a single hexadecimal digit as input from the user.
  • The function “hex_to_bin” is called, which takes the input digit and a character array to hold the binary representation as arguments.
  • The hexadecimal digit is first converted to its decimal equivalent using a series of conditional statements.
  • The decimal value is then converted to binary by repeatedly dividing by 2 and storing the remainder.
  • The binary string is reversed to get the correct order.
  • The binary representation is printed to the console.
  • The program terminates.

Program:

#include <stdio.h>
#include <string.h>

// Function to convert a single hexadecimal digit to binary
void hex_to_bin(char hex_digit, char *binary) {
    int decimal, i;
    if (hex_digit >= '0' && hex_digit <= '9') {
        decimal = hex_digit - '0';
    } else if (hex_digit >= 'a' && hex_digit <= 'f') {
        decimal = hex_digit - 'a' + 10;
    } else if (hex_digit >= 'A' && hex_digit <= 'F') {
        decimal = hex_digit - 'A' + 10;
    } else {
        printf("Invalid hexadecimal digit: %c\n", hex_digit);
        return;
    }

    if (decimal == 0) {
        binary[0] = '0';
        binary[1] = '\0';
        return;
    }

    for (i = 0; decimal > 0; i++) {
        binary[i] = decimal % 2 + '0';
        decimal /= 2;
    }
    binary[i] = '\0';

    // Reverse the binary string
    int j = i - 1;
    i = 0;
    while (i < j) {
        char temp = binary[i];
        binary[i] = binary[j];
        binary[j] = temp;
        i++;
        j--;
    }
}

int main() {
    char hex_string[256], binary_string[1024], binary_digit[5];
    int i;

    // Read in the hexadecimal string
    printf("Enter a hexadecimal string: ");
    scanf("%s", hex_string);

    // Convert each hexadecimal digit to binary and concatenate the results
    for (i = 0; i < strlen(hex_string); i++) {
        hex_to_bin(hex_string[i], binary_digit);
        strcat(binary_string, binary_digit);
    }

    // Print the original hexadecimal string and the resulting binary string
    printf("Hexadecimal input: %s\n", hex_string);
    printf("Binary output: %s\n", binary_string);

    return 0;
}

Output:

Enter a hexadecimal string: AB
Hexadecimal input: AB
Binary output: 10101011

Conclusion

In conclusion, there are different ways to convert hex to binary in C, such as using bitwise operators or recursive functions. Both methods involve breaking down the hex number into individual digits and converting them to binary. The bitwise operator approach uses special symbols to convert each digit and combine them into a binary number, while the recursive function approach involves repeatedly converting each digit and adding them to the binary number. Given approaches have their own advantages and the one you choose depends on your needs. Learning how to convert hex to binary in C is important for working with low-level programming and embedded systems.