source.io_library   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 23
dl 0
loc 49
rs 10
c 0
b 0
f 0
wmc 11

3 Functions

Rating   Name   Duplication   Size   Complexity  
A source_reader() 0 13 3
B output_writer() 0 18 7
A dec2bin() 0 9 1
1
import os
2
import struct
3
4
5
def source_reader(path: str) -> str:
6
    """ Reads source code
7
8
    :param path: string pointing to source code file location
9
    :return: source code
10
    """
11
    if not os.path.isfile(path):
12
        raise FileNotFoundError
13
    else:
14
        with open(path, 'r') as file:
15
            source = file.read()
16
17
    return source
18
19
20
def output_writer(path: str, header: list, object_dict: dict, mode: str):
21
    """ Writes compiled program
22
23
    :param path: output file path
24
    :param header: a list containing order of writing
25
    :param object_dict: dictionary containing bytes
26
    :param mode: switch between binary writing ('b') or textual writing ('t')
27
    """
28
    if mode == 'b':
29
        with open(path, 'wb+') as output:
30
            for memory_location in header:
31
                output.write(object_dict[memory_location])
32
    elif mode == 't':
33
        with open(path, 'w+') as output:
34
            for memory_location in header:
35
                integer = struct.unpack('>i', object_dict[memory_location])
36
                integer = integer[0]
37
                output.write(dec2bin(integer, 16) + '\n')
38
39
40
def dec2bin(decimal, bits) -> str:
41
    """ Converts a decimal number to it's 2nd complement binary representation
42
43
    :param decimal: decimal to be converted
44
    :param bits: number of bits for binary representation
45
    :return: string containing binary representation of decimal number
46
    """
47
    binary = bin(decimal & int("1" * bits, 2))[2:]
48
    return ("{0:0>%s}" % bits).format(binary)
49