-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTestConverter.java
More file actions
60 lines (60 loc) · 2.4 KB
/
TestConverter.java
File metadata and controls
60 lines (60 loc) · 2.4 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
public class TestConverter {
// fromInt converts a integer number to a binary number.
public static void fromInt(int value, Word32 result) {
// isNegative checks to see if the val is less than 0, if so prepare to negate it by adding 1 and conditionally manipulating the bits
// (depending on whether its a negative or not)
boolean isNegative = (value < 0);
int index = 31;
if(isNegative)
value++;
// while the value isn't 0, divide it by 2, if the remainder after being divided isn't true, then set it to 1 (or 0). If it's negative and odd, then
// also set the bit to true.
while(value != 0){
if(!isNegative && ((value % 2) == 0))
result.setBitN(index, new Bit(false));
else if(!isNegative && ((value % 2) != 0))
result.setBitN(index, new Bit(true));
else if(isNegative && ((value % 2) == 0))
result.setBitN(index, new Bit(true));
else
result.setBitN(index, new Bit(false));
index--;
value /=2;
}
// If after the value is 0 and there's still remaining indexes, will it with true
if(isNegative){
for(int i = index; i > -1; i--)
result.setBitN(i, new Bit(true));
}
// Else fill it with 0's (as typical for positive integers)
else{
for(int i = index; i > -1; i--)
result.setBitN(i, new Bit(false));
}
}
// toInt returns a Word32's value as a positive number. It uses twoPower to determine which powers of two are being used to create the
// final result. It gets the bit, and after getting its position within the binary number it adds by powers of 2 to the result.
public static int toInt(Word32 value) {
int fin = 0;
int adder = 0;
for(int i = 31; i > -1; i--){
Bit res = new Bit(false);
value.getBitN(i, res);
if(res.getValue() == Bit.boolValues.TRUE)
fin += twoPower(adder);
adder++;
}
return fin;
}
// twoPower takes an integer input and returns 2^pow
private static int twoPower(int pow){
if(pow == 0)
return 1;
else if(pow == 1)
return 2;
int fin = 2;
for(int i = 0; i < pow-1; i++)
fin *= 2;
return fin;
}
}