-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathTextToBin&BinToText.cpp
More file actions
74 lines (72 loc) · 1.73 KB
/
TextToBin&BinToText.cpp
File metadata and controls
74 lines (72 loc) · 1.73 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
#include <iostream>
#include <bitset>
#include <bits/stdc++.h>
using namespace std;
//Text To Binary//
string textToBin(string text){
string binary = "";
for (char& _char : text){
binary +=bitset<8>(_char).to_string();
}
return binary;
}
//Binary To Text//
int numerical(string temp){
int tempVal = 0;
reverse(temp.begin(), temp.end());
int base = 1;
for (int i = 0; i < temp.length(); i++){
if (temp[i] == '1')
tempVal += base;
base = base * 2;
}
return tempVal;
}
string binToText(string binary){
int n = int(binary.size());
if (n % 8 != 0){
return "No possible answer";
}
string text = "";
for (int i = 0; i < n; i += 8){
string temp = binary.substr(i, 8);
int num_val = numerical(temp);
char c = (char)(num_val);
text += c;
}
return text;
}
int main()
{
int selector ;
bool valid_input = false;
do{
int selector ;
cout <<"Select a option below..\n1.Text To Binary.\n2.Binary To Text.\n";
cin>>selector;
if(selector == 1){
valid_input = true;
while(true){
string text ;
cout << "Text:";
cin >> text;
cout << "Binary: " << textToBin(text) << "\n";
}
}
else if (selector == 2){
valid_input = true;
while(true){
string binary;
cout << "Binary:";
cin >> binary;
cout << "Text:" << binToText(binary) <<"\n";
}
}
else{
valid_input = false;
cout << "Worng Input!\n";
}
}
while (valid_input == false);
return 0;
}