This repository has been archived by the owner on Apr 16, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
88 lines (88 loc) · 2.39 KB
/
main.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
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
81
82
83
84
85
86
87
88
#include <iostream>
#include <iterator>
#include <list>
#include <string>
#include <locale>
#include <algorithm>
#include <stdexcept>
#include <chrono>
#include <thread>
#include <sstream>
using namespace std;
int binaryToDecimal(int n){
int num = n;
int dec_value = 0;
int base = 1;
int temp = num;
while (temp) {
int last_digit = temp % 10;
temp = temp / 10;
dec_value += last_digit * base;
base = base * 2;
}
return dec_value;
}
void decToBinary(int n){
int binaryNum[32];
int i = 0;
while (n > 0) {
binaryNum[i] = n % 2;
n = n / 2;
i++;
}
for (int j = i - 1; j >= 0; j--)
cout << binaryNum[j];
}
int main () {
using namespace std::this_thread;
using namespace std::chrono;
while(true){
cout <<"Do you want to convert from binary to decimal or decimal to binary?"<<endl<<"Please type 1 for binary to decimal,"<<endl<<"Please type 2 for decimal to binary,"<<endl<<"Please imput:";
int decbin;
cin >> decbin;
if (decbin == 1){
int num;
string::size_type num1;
while (true){
cout << "what is your binary number: ";
int tf;
cin >> num;
num1=num;
string str = to_string(num1);
cout << "debug:str," << str << endl;
cout << "debug:str.size,"<<str.size() <<endl;
cout << "debug:num1,"<< num1 << endl;
for(num1=0;num1<str.size();num1++){
if(str[num1]!='1' && str[num1]!='0'){
tf=1;
}
else{
tf=0;
}
}
if (tf==0){
break;
}
else{
cout <<"Invalid imput please imput a valid binary number."<<endl;
}
}
cout <<"Your number is : "<< binaryToDecimal(num) << endl;
cout <<"Your program returned with exit code of 0"<<endl<<"Please press run to run the program again.";
break;
}
else if (decbin==2){
cout << "Please input your decimal number:";
int n;
cin >> n;
cout <<"Your result is :";
decToBinary(n);
cout << endl <<"Your program returned with exit code of 0"<<endl<<"Please press run to run the program again.";
break;
}
else{
cout<<endl<< "Invalid selection."<<endl;
}
}
return 0;
}