-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.cpp
More file actions
80 lines (67 loc) · 1.9 KB
/
Main.cpp
File metadata and controls
80 lines (67 loc) · 1.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/*Write a program that converts decimal numbers to
binary, hexadecimal, and BCD. You are not allowed to use library functions
for conversion.*/
using namespace std;
#include <iostream>
#include <string>
// convert to binary
string convertToBin(int decimal) {
string num = "";
for (int i = 7; i >= 0; i--) {
int bit = (decimal >> i) & 1;
num += char('0' + bit);
}
num.insert(4, " "); // space every 4 bits
return num;
}
// convert to hex
string convertToHex(int decimal) {
if (decimal == 0) {
return "00";
}
string hexChars = "0123456789ABCDEF"; // for char mapping
string num = "";
while (decimal > 0) {
int remainder = decimal % 16;
num = hexChars[remainder] + num;
decimal /= 16;
}
return num;
}
// convert to BCD, format like "hhhh tttt oooo"
string convertToBCD(int decimal) {
int ones = decimal % 10;
int tens = (decimal / 10) % 10;
int hunds = (decimal / 100) % 10;
string BCD = "";
for (int digit : {hunds, tens, ones}) {
for (int i = 3; i >= 0; --i) {
int bit = (digit >> i) & 1; // shift bit right by i places
BCD.push_back('0' + bit);
}
BCD.push_back(' '); // for space every 4 bits
}
BCD.pop_back(); // removes last space
return BCD;
}
int main() {
int decimal;
cout << "Shahed Alabdulrahman, CIS-310-001, Pre-Test" << endl;
cout << "Enter decimal number: ";
cin >> decimal;
while (decimal != -1) {
if (decimal < 0 || decimal > 255) {
cout << "Invalid! Number must be between 0 and 255." << endl << endl;
}
else {
string binary = convertToBin(decimal);
string hex = convertToHex(decimal);
string BCD = convertToBCD(decimal);
cout << "Binary Hexidecimal BCD" << endl;
cout << binary << " " << hex << " " << BCD << endl;
}
cout << "Enter decimal number (0-255) or -1 to quit: ";
cin >> decimal;
}
return 0;
}