-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy path2s'-complement.cpp
More file actions
55 lines (51 loc) · 1.12 KB
/
2s'-complement.cpp
File metadata and controls
55 lines (51 loc) · 1.12 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
#include <iostream>
#define size 4
using namespace std;
int main()
{
char binary[size + 1], one[size + 1], two[size + 1];
int i, carry = 1, fail = 0;
cout << " Enter a " << size << " bit binary number: ";
cin >> binary;
for (i = 0; i < size; i++)
{
if (binary[i] == '1')
{
one[i] = '0';
}
else if (binary[i] == '0')
{
one[i] = '1';
}
else
{
cout << "Error! Input the number of assigned bits." << endl;
fail = 1;
break;
}
}
one[size] = '\0';
for (i = size - 1; i >= 0; i--)
{
if (one[i] == '1' && carry == 1)
{
two[i] = '0';
}
else if (one[i] == '0' && carry == 1)
{
two[i] = '1';
carry = 0;
}
else
{
two[i] = one[i];
}
}
two[size] = '\0';
if (fail == 0)
{
cout << " The original binary = " << binary << endl;
cout << " Ones complement = " << one << endl;
cout << " Twos complement = " << two << endl;
}
}