C Program to Convert Binary to Hexadecimal

0

Method 1

#include <stdio.h>
 
#include <string.h>
 
int main()
{
 
    int hexConstant[] = {0, 1, 10, 11, 100, 101, 110, 111, 1000, 1001, 1010, 1011, 1100, 1101, 1110, 1111};
 
    long long binary, tempBinary;
 
    char hex[20];
     
    int index, i, digit;
     
    /* Input binary number from user */
    printf("Enter binary number: ");
     
    scanf("%lld", &binary);
     
    /* Copy binary number to temp variable */
    tempBinary = binary;
     
    index = 0;
     
    /* Find hexadecimal of binary number */
    while(tempBinary!=0)
    {
     
        /* Group binary to last four digits */
        digit = tempBinary % 10000;
 
        /* Find hexadecimal equivalent of last four digit */
        for(i=0; i<16; i++)
     
        {
     
            if(hexConstant[i] == digit)
     
            {
     
                if(i<10)
     
                {
     
                    /* 0-9 integer constant */
                    hex[index] = (char)(i + 48);
     
                }
     
                else
     
                {
     
                    /* A-F character constant */
                    hex[index] = (char)((i-10) + 65);
     
                }
 
                index++;
     
                break;
            }
        }
 
        /* Remove the last 4 digits as it is processed */
        tempBinary /= 10000;
    }
     
    hex[index] = '\0';
 
    /* Reverse the hex digits */
     
    strrev(hex);
 
    printf("Binary number = %lld\n", binary);
     
    printf("Hexadecimal number = %s", hex);
 
    return 0;
}

Output

Enter binary number: 01101110
Binary number = 1101110
Hexadecimal number = 6E

Method 2

#include<stdio.h>
 
#include<conio.h>
 
void main()
 
{
 
    clrscr();
 
    long int decnum, rem, quot;
 
    int i=1, j, temp;
 
    char hexdecnum[100];
 
    printf("Enter binary number : ");
 
    scanf("%ld",&decnum);
 
    quot = decnum;
 
    while(quot!=0)
 
    {
        temp = quot % 16;
 
        // To convert integer into character
        if( temp < 10)
 
        {
            temp = temp + 48;
        }
 
        else
 
        {
            temp = temp + 55;
        }
 
        hexdecnum[i++]= temp;
 
        quot = quot / 16;
    }
 
    printf("Equivalent hexadecimal value of %d is :\n",decnum);
 
    for(j=i-1 ;j>0;j--)
 
    {
        printf("%c",hexdecnum[j]);
    }
 
    getch();
}

Output

Enter binary number: 01101110
Equivament Hexadecimal value of 01101110 is = 6E

Leave a Reply

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