forked from allenmadd/html
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path8binTest.cpp
More file actions
52 lines (49 loc) · 812 Bytes
/
8binTest.cpp
File metadata and controls
52 lines (49 loc) · 812 Bytes
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
#include <iostream>
#include <cmath>
#include <string>
#include <cstdlib>
using namespace std;
int binConv(string n)
{
//output the error message
if(n.size()!=8)
{
cerr<<"Usage: 8binConv <8-bit binary number>\n";
exit(1);
}
//convert from char to int(ASCII)
else
{
int decimal(0);
for(int i=0;i<8;i++)
{
decimal+=(int(n[i])-48)*pow(2,7-i);
}
return decimal;
}
}
//convert the decimal to binary and reverse the string
string convert(int decimal)
{
string sum="";
while(decimal!=0)
{
sum+=to_string(decimal%2);
decimal/=2;
}
while(sum.size()!=8)
{
sum+=to_string(0);
}
sum=string(sum.rbegin(),sum.rend());
return sum;
}
int main()
{
//print out the output
for(int i=0;i<256;i++)
{
cout<<"Binary number "<< convert(i)<<" is decimal number "<<i<<endl;
}
return 0;
}