Binary to Hexadecimal Conversion in C++

Hexadecimal is a number system which have 16 characters in its counting that are 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F
Each Character of Hex System is Equal to a 4 Digit Binary…. like 0 = 0000 , 3 = 0011 , 8 = 1000, C = 1100, F = 1111…
Table of Number Systems is given blow

Number System Table


To Convert binary number to a hex number.. we simply need to extend our binary number and make sure digits are multiple of 4…
for Example if we are given with 100101 .. we have to append 0’s on it’s left side to make it of Length 8 because 8 is multiple of 4..
So 100101 will become 00100101 … now starting from right side, we need to make chunks of it of length 4…
So it will become 0010 0101 ,,,,,,,, now in table find Equivalent Character in Table… 0010 is 2… and 0101 is 5… so it will become 25.
Hence 100101 is 25 in Hex System
Another way to Do it is to Convert Binary to Decimal and then Take LCM of Decimal Number with 16 to get it’s Hexa Equivalent..
For Example 100101 as we know is equal to 37 in Decimal… So taking LCM of 37 with 16
16 | 37
| 2 – 5
So 25 is Answer…

Code for Binary to Hexadecimal

//Binary to Hex
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
	char arr[100];
	long int dec=0,i,j;
	char hex[50];
	cout<<"Enter binary "<<endl;
	cin>>arr;
	for(i=0;arr[i]!='\0';i++);
	for(i=i-1,j=0;i>=0;i--,j++)
	{
		dec+=(arr[j]-48)*pow(2,i);
	}
	for(i=0;dec>0;i++)
	{
		if(dec%16<10)
		hex[i]=dec%16+48;
		else
		hex[i]=dec%16+55;
		dec=dec/16;
	}
	cout<<"\nHex equivalent"<<endl;
	for(i=i-1;i>=0;i--)
	cout<<hex[i];
}

Output:

Enter binary
100101

Hex equivalent
25

Related Post

Leave a Reply

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