-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary_conversions.cpp
47 lines (43 loc) · 1.04 KB
/
binary_conversions.cpp
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
#include <iostream>
#include <stack>
#include <string>
using namespace std;
string divideBy2(int decimal)
{
stack<int> remainderStack;
while (decimal > 0)
{
int remainder = decimal%2;
remainderStack.push(remainder);
decimal = decimal/2;
}
string output;
while (!remainderStack.empty())
{
output += to_string(remainderStack.top());
remainderStack.pop();
}
return output;
}
string baseConverter(int decimal, int base)
{
string digits [] = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"};
stack<string> remainderStack;
while (decimal > 0)
{
remainderStack.push(digits[decimal%base]);
decimal /= base;
}
string output;
while (!remainderStack.empty())
{
output += remainderStack.top();
remainderStack.pop();
}
return output;
}
void test_binary()
{
cout << divideBy2(23) << " = 10111" << endl;
cout << "6423453 to base 16: " << baseConverter(6423453 , 16) << " = 62039D" <<endl;
}