Convert Binary to Hexadecimal program in C++

Convert Binary-Hexadecimal program

Binary Number: A binary number is a number expressed in the base-2 binary numeral system, using only two symbols: which are 0 (zero) and 1 (one).

HexaDecimal Number: A hexadecimal number is a positional numeral system with base 16 and uses sixteen distinct symbols (0 to 15).

Example:

Binary number: 10110

Equivalent Hexadecimal Number: 16

Binary number: 101010

Equivalent Hexadecimal Number: 2A

# Algorithm

  1. Take a binary number as input.
  2. Group all binary bits to 4 digits (starting from the right side).
  3. Write the corresponding hexadecimal value of each grouped digit.

Code:

#include <iostream>
using namespace std;

int main() {
    char binaryNumber[1000], hexadecimalNumber[1000];
    int temp;
    long int binaryIndex = 0, hexadecimalIndex = 0;
    
    cout << "Enter Binary Number: ";
    cin >> binaryNumber;
    
    while (binaryNumber[binaryIndex]) {
        binaryNumber[binaryIndex] = binaryNumber[binaryIndex] - 48;
        ++binaryIndex;
    }
    --binaryIndex;
    
    while (binaryIndex - 2 >= 0) {
        temp = binaryNumber[binaryIndex - 3] * 8 + binaryNumber[binaryIndex - 2] * 4 + binaryNumber[binaryIndex - 1] * 2 + binaryNumber[binaryIndex];
        if (temp > 9) {
            hexadecimalNumber[hexadecimalIndex++] = temp + 55;
        } else {
            hexadecimalNumber[hexadecimalIndex++] = temp + 48;
        }
        binaryIndex = binaryIndex - 4;
    }
    
    if (binaryIndex == 1) {
        hexadecimalNumber[hexadecimalIndex] = binaryNumber[binaryIndex - 1] * 2 + binaryNumber[binaryIndex] + 48;
    } else if (binaryIndex == 0) {
        hexadecimalNumber[hexadecimalIndex] = binaryNumber[binaryIndex] + 48;
    } else {
        --hexadecimalIndex;
    }
    
    cout << "\nHexadecimal Number equivalent to Binary Number: ";
    while (hexadecimalIndex >= 0) {
        cout << hexadecimalNumber[hexadecimalIndex--]
    }
    
    return 0;
}

Output

Enter Binary Number: 1010101
Hexadecimal Number equivalent to Binary Number: 155

Convert Binary to Hexadecimal program in C++