In: Computer Science
Write a program in C++ that converts decimal numbers to binary, hexadecimal, and BCD. You are not allowed to use library functions for conversion. The output should look exactly as follows:
DECIMAL BINARY HEXDECIMAL BCD
0 0000 0000 00 0000 0000 0000
1 0000 0001 01 0000 0000 0001
2 0000 0010 02 0000 0000 0010
. . . .
. . . .
255 1111 1111 FF 0010 0101 0101
Code
#include <iostream>
#include <string>
using namespace std;
string decimaltobinary(int x)
{
string binary = "";
while (x)
{
binary = ((x % 2) ? "1" : "0") +
binary;
x =x / 2;
if (binary.length() == 4)
binary = " " +
binary; // Formatting
}
// Formatting
while (binary.length() != 9)
{
binary = "0" + binary; // Adjusting
length as 8 bit binary
if (binary.length() == 4)
binary = " " +
binary; // Formatting
}
return binary;
}
string decimaltohex(int x)
{
string hex = "";
while (x)
{
int rem = x % 16; // taking
remainder
string temp;
if (rem < 10)
temp =
to_string(rem);
else
{
switch
(rem)
{
case 10:
temp = "A";
break;
case 11:
temp = "B";
break;
case 12:
temp = "C";
break;
case 13:
temp = "D";
break;
case 14:
temp = "E";
break;
case 15:
temp = "F";
break;
}
}
hex = temp + hex;
x = x / 16;
}
while (hex.length() != 2)
hex = "0" + hex; // Adjusting
length as 2 hex
return hex;
}
string decimaltobcd(int x)
{
string bcd = "";
while (x)
{
int rem = x % 10; // taking
remainder
string temp;
switch (rem)
{
case 0:
temp =
"0000";
break;
case 1:
temp =
"0001";
break;
case 2:
temp =
"0010";
break;
case 3:
temp =
"0011";
break;
case 4:
temp =
"0100";
break;
case 5:
temp =
"0101";
break;
case 6:
temp =
"0110";
break;
case 7:
temp =
"0111";
break;
case 8:
temp =
"1000";
break;
case 9:
temp =
"1001";
break;
}
bcd = temp + " " + bcd;
x = x / 10;
}
while (bcd.length() != 15)
bcd = "0000 " + bcd; // Adjusting
length as 8 bit binary
return bcd;
}
int main()
{
int i = 0;
cout << "DECIMAL \t BINARY \t HEXADECIMAL \t\t
BCD"<<endl;
while (i < 256)
{
cout << i << "\t\t"
<< decimaltobinary(i) << "\t\t" <<
decimaltohex(i) << "\t\t" << decimaltobcd(i) <<
endl;
i++;
}
return 0;
}
Test Output