Convert ASCII Character to Hexadecimal and Binary using C++
Posted by Samath
Last Updated: January 05, 2017

This program ask the user for a ASCII Character and convert it to Hexadecimal and Binary.

Hexadecimal is a positional numeral system with a radix, or base, of 16. It uses sixteen distinct symbols, most often the symbols 0–9 to represent values zero to nine, and A, B, C, D, E, F (or alternatively a, b, c, d, e, f) to represent values ten to fifteen.

#include <iostream>
using namespace std;

int x; 
char xa; 
int y; 
int n = 0;
int i = 0; 
int a = 0; 
int binary[8] = { 128, 64, 32, 16, 8, 4, 2, 1 };
int binaryout[8];
int nibbleone[4];
int nibbletwo[4];
char hexvalue[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
int b; 
int c; 
int d;
int e;


int main()
{
	cout << "Input any character: ";
	cin >> xa;
	x = xa; 
	cout << "ASCII value: " << x << endl;

	for (y = 0; y <= 7; y++)
	{
		if (x == 0)
		{
			break;
		}
		if (x - binary[y] >= 0)
		{
			x -= binary[y];
			binaryout[n] = 1;
			n += 1;
		}
		else if (x - binary[y] < 0)
		{
			n += 1;
		}
	}

	cout << "Binary Value: ";

	for (i = 0; i <= 7; i++)
	{
		cout << binaryout[i];

		if (i < 4)
		{
			nibbleone[a] = binaryout[i];
			a += 1;
		}
		else if (i == 4)
		{
			a = 0;
			nibbletwo[a] = binaryout[i];
			a += 1;
		}
		else if (i > 4)
		{
			nibbletwo[a] = binaryout[i];
			a += 1;
		}
	}

	e = 4;

	for (d = 0; d <= 3; d++)
	{
		if (nibbleone[d] == 1)
		{
			b += binary[e];
			e += 1;
		}
		else if (nibbleone[d] == 0)
		{
			e += 1;
		}
	}

	cout << endl << "Hex value: " << hexvalue[b];

	e = 4;

	for (d = 0; d <= 3; d++)
	{
		if (nibbletwo[d] == 1)
		{
			c += binary[e];
			e += 1;
		}
		else if (nibbletwo[d] == 0)
		{
			e += 1;
		}
	}

	cout << hexvalue[c] << endl;

	int end;
	cin >> end;
}