C Program to Convert Binary to Hexadecimal

This C program converts a binary number to its hexadecimal equivalent.

Problem Statement

Write a program that takes a binary number as input and converts it to its hexadecimal representation.

C Program to Convert Binary to Hexadecimal

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

// Function to convert binary to hexadecimal
void binaryToHexadecimal(char binary[])
{
    // Length of the binary number
    int length = strlen(binary);
    
    // Calculating the number of digits required in hexadecimal
    int hexLength = (length + 3) / 4;
    
    // Padding the binary number with leading zeros if necessary
    int paddingZeros = hexLength * 4 - length;
    for (int i = 0; i < paddingZeros; i++)
    {
        printf("0");
    }
    
    // Converting each group of 4 binary digits to hexadecimal
    for (int i = 0; i < length; i += 4)
    {
        int decimal = 0;
        
        // Converting binary to decimal
        for (int j = 0; j < 4; j++)
        {
            decimal = decimal * 2 + (binary[i + j] - '0');
        }
        
        // Converting decimal to hexadecimal
        if (decimal < 10)
        {
            printf("%c", decimal + '0');
        }
        else
        {
            printf("%c", decimal - 10 + 'A');
        }
    }
    
    printf("\n");
}

int main()
{
    char binary[100];
    
    printf("Binary to Hexadecimal Converter\n");
    printf("-------------------------------\n");
    printf("Enter a binary number: ");
    scanf("%s", binary);
    
    printf("Hexadecimal equivalent: ");
    binaryToHexadecimal(binary);
    
    return 0;
}

How it works

  1. The program defines a function called binaryToHexadecimal that takes a binary number as input and converts it to its hexadecimal equivalent.
  2. The function calculates the number of hexadecimal digits required based on the length of the binary number.
  3. It then pads the binary number with leading zeros if necessary to form complete groups of 4 digits.
  4. The function processes each group of 4 binary digits and converts them to decimal.
  5. Finally, it converts the decimal value to its corresponding hexadecimal representation and prints the result.

Input / Output

C Program to Convert Binary to Hexadecimal

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

This C program finds the Greatest Common Divisor (GCD) of two given numbers. Problem Statement Write a C program that...
This C program calculates the roots of a quadratic equation of the form ax^2 + bx + c = 0....
This C program allows you to find the length of a linked list, which is the number of nodes present...