-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
111 lines (68 loc) · 2.27 KB
/
main.py
File metadata and controls
111 lines (68 loc) · 2.27 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
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
class ALU:
def __init__(self):
self.flags = {
'Z':0,
'N':0,
'O':0
}
def halfAdder(self,a,b):
sum_bit = a^b
carry_bit = a&b
return sum_bit, carry_bit
def fullAdder(self,a,b,carry_in):
sum1, carry1 = self.halfAdder(a,b)
sum_bit,carry2 = self.halfAdder(sum1, carry_in)
carry_out = carry1 | carry2
return sum_bit, carry_out
def add8Bit(self, byteA, byteB):
byteA = byteA & 0xFF
byteB = byteB & 0xFF
resultBits = []
carry = 0
for i in range(8):
bitA = (byteA >> i) & 1
bitB = (byteB >> i) & 1
sum_bit, carry = self.fullAdder(bitA, bitB, carry)
resultBits.append(sum_bit)
result = 0
for i, bit in enumerate(resultBits):
result |= bit <<i
self.finalCarry = carry
result &= 0xFF
return result
def twosComplement(self, byte):
invert = ~byte & 0xFF
return self.add8Bit(invert,1)
def sub8Bit(self, byteA, byteB):
negativeB = self.twosComplement(byteB)
return self.add8Bit(byteA, negativeB)
def updateFlags(self, result, a, b, isSubtraction = False):
if result ==0:
self.flags['Z'] = 1
else:
self.flags['Z'] = 0
if result & 0x80 !=0:
self.flags['N'] = 1
else:
self.flags['N'] = 0
aSign = (a & 0x80) >> 7
bSign = (b & 0x80) >> 7
resultSign = (result & 0x80) >>7
if isSubtraction:
bSign = 1-bSign
if aSign == bSign and resultSign != aSign:
self.flags['O'] = 1
else:
self.flags['O'] = 0
def execute(self, opcode, byteA, byteB):
byteA = byteA & 0xFF
byteB = byteB & 0xFF
if opcode == 0:
result = self.add8Bit(byteA, byteB)
self.updateFlags(result, byteA, byteB, isSubtraction= False)
elif opcode == 1:
result = self.sub8Bit(byteA, byteB)
self.updateFlags(result, byteA, byteB, isSubtraction= True)
else:
raise ValueError(f"Invalid opcode: {opcode}")
return result