In this shot, we will discuss how to convert a number from binary to hexadecimal in C++.
To convert a binary number to a hexadecimal number, we take four digits from the right-most part of the binary form to divide it into two sets. If there are less than four digits on the left, add extra zeros to the binary number. Then, the number is multiplied by ().
Let’s look at the image below to understand how this conversion works.
In the above image, the binary number is divided into sets of four digits and then multiplied by from right to left, with the power of increasing in the same direction.
In this case, there are less than four digits on the left side once the set of four is made on the right, so we add 0
to that value as shown in the image above. The value of binary number 1101110
in hexadecimal form is 6E
.
Let’s look at the below code snippet to understand it in a better way.
#include <iostream>using namespace std;int main() {int hex[1000];int i = 1, j = 0, rem, dec = 0, binaryNumber;cin>> binaryNumber;while (binaryNumber > 0){rem = binaryNumber % 2;dec = dec + rem * i;i = i * 2;binaryNumber = binaryNumber / 10;}i = 0;while (dec != 0){hex[i] = dec % 16;dec = dec / 16;i++;}cout<<" The hexadecimal value: ";for (j = i - 1; j >= 0; j--){if (hex[j] > 9)cout<<(char)(hex[j] + 55)<<"\n";elsecout<<hex[j];}return 0;}
Enter the input below
Enter a binary number in the input section above.
In lines 5 and 6, we initialize the variables hex
, i
, j
, dec
, rem
, and binaryNumber
.
In line 7, we take binaryNumber
as input.
From lines 8 to 21, we initialize a while
loop. In the loop, we calculate the remainders and quotients, as we discussed in the above illustration, to convert the binary number to its hexadecimal equivalent.
In line 23, we print the output, i.e., the hexadecimal equivalent of the binary number.
From lines 23 to 30, we initialize a for
loop where we have given conditions to print an integer value if the value is less than 9
. Otherwise, we print the character value.