-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinNum.java
146 lines (94 loc) · 2.94 KB
/
BinNum.java
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
/* Class to store integers between -128 and 127 as
an array of 8 booleans. Two's complement will be used to
deal with negative integers.
*/
/*
* Binary Conversion HW 1
* AD 315
* @author: Sam Cooledge
* */
public class BinNum {
public static final int BINARY = 8;
//Create a boolean array
public boolean[] binary;
/*
* constructor
* @param int n
* */
public BinNum(int n) {
//create alias for boolean array
binary = new boolean[8];
int index = 0;
//while loop sets condition for for 8 index spaces
while(index < 8){
//if number(51) % 2 = 1 then it is true(1)
if(n%2 == 1){
// targets the last index point
binary[7-index] = true;
}
//else number(51) % 2 != 1 then it is false(0)
else
binary[7-index] = false;
//with each iteration for index position, number is divided by 2
n/=2;
//updates index position to next
index++;
}
}
public static BinNum add(BinNum a, BinNum b) {
//create new BinNum named c
BinNum c = new BinNum(0);
//create carry reference, set it to false
boolean carry = false;
//for loop set up to target the last index position
for(int i = BINARY -1; i >= 0; i--){
//use new refence c
// use "exclusive or" operator to a,b, and carry.
c.binary[i] = a.binary[i] ^ b.binary[i] ^ carry;
int count = 0;
//if statement to target index of a and b and update count
if(a.binary[i]) count++;
if(b.binary[i]) count++;
if(carry) count++;
//carry gets set to 2 or 3
carry = (count ==2 || count == 3) ;
}
return c;
}
//private void negate() {
//displays the binary number
private void displayByteNum() {{
System.out.println("Binary: " );
}
for(int i = 0 ; i < binary.length; i++) {
if(binary[i] == true)
System.out.print(1);
else
System.out.print(0);
}
System.out.println();
}
//converts binary to int
private void displayNum() {
System.out.println("Back to Ints: ");
int count = 0;
int power = 1;
for(int i = BINARY-1; i >= 0; i--) {
if(binary[i] == true) {
count += 1*power;
}
power *= 2;
}
System.out.println(count);
}
public static void main(String[] args) {
BinNum a = new BinNum(51);
BinNum b = new BinNum(4);
a.displayByteNum();
b.displayByteNum();
BinNum c = add(a,b);
c.displayByteNum();
a.displayNum();
b.displayNum();
}
}