This repository has been archived by the owner on May 9, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SB_format.py
73 lines (61 loc) · 2.7 KB
/
SB_format.py
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
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 15 23:48:03 2020
@author: SARVESH
"""
isa={
'beq' :{'opcode':'1100011', 'fun3':'000'},
'bne' :{'opcode':'1100011', 'fun3':'001'},
'blt' :{'opcode':'1100011', 'fun3':'100'},
'bge' :{'opcode':'1100011', 'fun3':'101'}
}
class MyException(Exception):
pass
def SB_format(instruction):
instruction=instruction.replace(" ",",")
instruction_arr=instruction.split(",")
while "" in instruction_arr:
instruction_arr.remove("")
############################################################################
if(len(instruction_arr)!=4):
raise MyException("Expected three arguements!")
try:
int(instruction_arr[3])
except:
raise MyException("Immediate Value must be an Integer!")
if int(instruction_arr[3]) > 4094 or int(instruction_arr[3]) < -4096:
raise MyException("Immediate value out of bounds!")
###############################################################################
machine_code=[]
if (int(instruction_arr[3]))>=0:
immediate=bin(int(instruction_arr[3])).replace("0b","").rjust(12,'0')
else:
immediate=bin(2**12+int(instruction_arr[3])).replace("0b","").rjust(12,'0')
immediate_rev=immediate[::-1]
if 'x' not in instruction_arr[1] or 'x' not in instruction_arr[2]:
raise MyException("Enter register numbers in correct format")
instruction_arr[1]=instruction_arr[1].replace('x','')
instruction_arr[2]=instruction_arr[2].replace('x','')
#########################
try:
int(instruction_arr[1])
int(instruction_arr[2])
except:
raise MyException("Register number must be an Integer!")
if(int(instruction_arr[1])>31 or int(instruction_arr[2])>31):
raise MyException("Register number must be between 0 and 31, both inclusive.")
#########################
machine_code.append(immediate_rev[11])
machine_code.append(immediate_rev[5:10])
machine_code.append(bin(int(instruction_arr[2])).replace("0b", "").rjust(5, '0'))
machine_code.append(bin(int(instruction_arr[1])).replace("0b", "").rjust(5, '0'))
machine_code.append(isa[instruction_arr[0]]['fun3'])
machine_code.append(immediate_rev[1:5])
machine_code.append(immediate_rev[10])
machine_code.append(isa[instruction_arr[0]]['opcode'])
print(machine_code)
while "" in machine_code:
machine_code.remove("")
machine_bin=machine_code[0]+machine_code[1]+machine_code[2]+machine_code[3]+machine_code[4]+machine_code[5]+machine_code[6]+machine_code[7]
machine_hex="{:08x}".format((int(machine_bin,2)))
return "0x" + machine_hex