The Program in C++ to Convert Binary Number to hexadecimal number is given below:
#include <iostream>
#include <string>
using namespace std;
string binaryToHex(string binary) {
string hex = "";
for (int i = 0; i < binary.length(); i += 4) {
string temp = binary.substr(i, 4);
int decimal = stoi(temp, 0, 2);
if (decimal >= 0 && decimal <= 9) {
hex += (char)(decimal + '0');
}
else {
hex += (char)(decimal - 10 + 'A');
}
}
return hex;
}
int main() {
string binary;
cout << "Hello Codeauri Family,Enter a binary number to convert them into hexadecimal: \n";
cin >>binary;
cout << "Well,the hexadecimal equivalent is: " << binaryToHex(binary) << endl;
return 0;
}
Output:
Hello Codeauri Family,Enter a binary number to convert them into hexadecimal:
10
Well,the hexadecimal equivalent is: 2
Pro-Tips💡
This program prompts the user to enter a binary number, then uses a function called “binaryToHex” to convert the number to hexadecimal.
The hexadecimal equivalent is then output to the console. The binaryToHex function does the following:
- It groups the binary number in groups of 4 digits starting from the right
- It converts each group of 4 digits to decimal
- For each decimal number between 0 and 9, it converts it to its corresponding ASCII character
- For each decimal number between 10 and 15, it converts it to its corresponding ASCII character between ‘A’ and ‘F’.
- Finally it returns the final hexadecimal string. Note that this implementation assumes that the binary number is a multiple of 4, if not the last group of digits will be padded with zeroes.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.