29 Commits

Author SHA1 Message Date
Rhinemann c5e6b61931 README updated. 2024-01-18 23:41:43 +02:00
Rhinemann 02031c1102 README updated. 2024-01-18 23:29:10 +02:00
Rhinemann 054dc803d1 README expanded. 2024-01-18 23:27:32 +02:00
Rhinemann 9f7ec834b2 Merge pull request 'Implement all methods for binary division' (#4) from division-implementation into master
Reviewed-on: #4
2023-07-30 10:25:27 +03:00
dymik739 a387325077 remove unused get_mantice_complement() function 2023-07-29 20:57:51 +03:00
dymik739 f31491cdad fix first division method, ready for merging 2023-07-29 20:50:40 +03:00
dymik739 91fc4084e1 implemented division method 2, method 1 still needs work 2023-07-29 18:42:06 +03:00
Rhinemann c8fb25025c Changed BasicRegister.__init__() to accept decue instead of a list.
Inherited Counter from BasicRegister.
2023-06-28 14:49:35 +03:00
Rhinemann f1d348616a Merge pull request 'Add binary multiplication functions' (#3) from multiplication-implementation into master
Reviewed-on: #3
2023-06-28 14:19:28 +03:00
dymik739 9e06a93c19 remove redundant method: BasicRegister.compact_str() 2023-06-28 12:59:25 +03:00
dymik739 4e0e30383d add multiplication logging, include prettytable library and update input_handler menu structure 2023-06-28 12:36:02 +03:00
Rhinemann 421a94b195 Renamed reverse to negate. 2023-06-27 22:47:13 +03:00
dymik739 5a26802c34 optimize binary_sum_with_carry function by removing code repetition 2023-06-27 22:09:45 +03:00
dymik739 9925c22954 add support for all multiplication methods and extend input_handler menu structure 2023-06-27 22:00:15 +03:00
Rhinemann 6afb9151fe Documented all methods and functions. 2023-06-27 17:53:18 +03:00
Rhinemann 32cf1e8712 Documented all methods and functions. 2023-06-27 17:49:33 +03:00
Rhinemann c20aef323d Rewrote align_registers to accept any number of registers. 2023-06-27 17:49:03 +03:00
Rhinemann 32605e4b49 Introduced binary_sum_with_carry and rewrote binary_sum accordingly. 2023-06-27 17:05:40 +03:00
Rhinemann 0f94f6d37a Minor rewrites. 2023-06-27 16:43:18 +03:00
Rhinemann 9fedc98310 Implemented input_handler function. 2023-06-27 16:40:09 +03:00
Rhinemann b3c5011c11 Revamped function scopes. 2023-06-27 15:53:20 +03:00
Rhinemann f477c6f9e1 binary_subtraction_1_complement initial commit. 2023-06-27 15:34:39 +03:00
Rhinemann 544031efbb Just some testing. 2023-06-27 14:18:37 +03:00
Rhinemann d2df4bbf28 Renamed arguments inside binary_sum.
Added carry return (VERY NOT SURE IF IT WORKS CORRECTLY).
2023-06-27 14:18:10 +03:00
Rhinemann 132a0b5659 Changed the conditions checking register lengths. 2023-06-27 14:09:07 +03:00
Rhinemann 75f7dba546 Implemented __repr__ and __len__ for BasicRegister. 2023-06-27 14:07:47 +03:00
dymik739 f2ee4cd709 fix BasicRegister shrinking 2023-06-26 22:33:41 +03:00
Rhinemann 8f68099309 Minor adjustments to bitutilities.py. 2023-06-26 21:58:24 +03:00
Rhinemann a9cfd1ec97 Merge pull request 'Core: add the sum function for BasicRegister objects' (#1) from feature-sum into master
Reviewed-on: #1
2023-06-26 21:29:25 +03:00
3 changed files with 803 additions and 68 deletions
+256 -1
View File
@@ -1,3 +1,258 @@
# binaryCalculatorPrototype
This is a Python language prototype for a binary calculator to be used in Computer Arithmetics lab works for first-year students studying Computer Engineering at KPI.
This is a Python language prototype for a binary calculator to be used in Computer Arithmetics lab works for first-year students studying Computer Engineering at KPI.
# Requirements
The user must have installed:
- python 3 (for the calculator itself);
- git (to clone the repository for installation);
# Installation
To install the calculator just clone the repository locally:
```
git clone -b master http://139.162.162.130:3000/Rhinemann/binaryCalculatorPrototype.git
```
# User instructions
Start the calculator using the following command:
```
python3 main.py
```
After that you must input the binary number as your first and second operands, as such:
```
Enter first operand: 110101
Enter second operand: 110
```
Note that you can't input any digit other than 0 or 1 into the operands:
```
Enter first operand: 234123
[ERROR] The first operand may contain only 1-s and 0-s!
Enter first operand: 12314
[ERROR] The first operand may contain only 1-s and 0-s!
Enter first operand: 1234123
[ERROR] The first operand may contain only 1-s and 0-s!
```
After properly inputting the operands properly, you will be presented with such prompt:
```
Choose the operation:
[a]ddition, [s]ubtraction, [m]ultiplication, [d]ivision, [q]uit
(110101 000110) >
```
`(110101 000110)` are the operands you have input. You may now choose the operations performed on the operands as such:
```
Choose the operation:
[a]ddition, [s]ubtraction, [m]ultiplication, [d]ivision, [q]uit
(110101 000110) > a
Sum: 111011
Carry: 0
Choose the operation:
[a]ddition, [s]ubtraction, [m]ultiplication, [d]ivision, [q]uit
(110101 000110) > s
Subtraction: 101111
Carry: 1
Choose the operation:
[a]ddition, [s]ubtraction, [m]ultiplication, [d]ivision, [q]uit
(110101 000110) > m
Choose method to use (1-4):
(110101 000110) m > 1
Multiplication (method 1):
+------+--------+--------+--------+-----+----------------------+
| iter | RG1 | RG2 | RG3 | CT | MicroOperations |
+------+--------+--------+--------+-----+----------------------+
| 0 | 000000 | 110101 | 000110 | 110 | - |
+------+--------+--------+--------+-----+----------------------+
| 1 | 000110 | 110101 | 000110 | 110 | RG1 := RG1 + RG3 |
| 1 | 000011 | 011010 | 000110 | 101 | RG2 := RG1[1].r(RG2) |
| | | | | | RG1 := 0.r(RG1) |
| | | | | | CT := CT - 1 |
+------+--------+--------+--------+-----+----------------------+
| 2 | 000001 | 101101 | 000110 | 100 | RG2 := RG1[1].r(RG2) |
| | | | | | RG1 := 0.r(RG1) |
| | | | | | CT := CT - 1 |
+------+--------+--------+--------+-----+----------------------+
| 3 | 000111 | 101101 | 000110 | 100 | RG1 := RG1 + RG3 |
| 3 | 000011 | 110110 | 000110 | 011 | RG2 := RG1[1].r(RG2) |
| | | | | | RG1 := 0.r(RG1) |
| | | | | | CT := CT - 1 |
+------+--------+--------+--------+-----+----------------------+
| 4 | 000001 | 111011 | 000110 | 010 | RG2 := RG1[1].r(RG2) |
| | | | | | RG1 := 0.r(RG1) |
| | | | | | CT := CT - 1 |
+------+--------+--------+--------+-----+----------------------+
| 5 | 000111 | 111011 | 000110 | 010 | RG1 := RG1 + RG3 |
| 5 | 000011 | 111101 | 000110 | 001 | RG2 := RG1[1].r(RG2) |
| | | | | | RG1 := 0.r(RG1) |
| | | | | | CT := CT - 1 |
+------+--------+--------+--------+-----+----------------------+
| 6 | 001001 | 111101 | 000110 | 001 | RG1 := RG1 + RG3 |
| 6 | 000100 | 111110 | 000110 | 000 | RG2 := RG1[1].r(RG2) |
| | | | | | RG1 := 0.r(RG1) |
| | | | | | CT := CT - 1 |
+------+--------+--------+--------+-----+----------------------+
Result: 000100111110
Choose the operation:
[a]ddition, [s]ubtraction, [m]ultiplication, [d]ivision, [q]uit
(110101 000110) > d
Choose method to use (1-2):
(110101 000110) d > 1
Division (method 1):
+------+---------+----------+----------+-----------------------+
| iter | RG3 | RG2 | RG1 | MicroOperations |
+------+---------+----------+----------+-----------------------+
| 0 | 1111111 | 00110101 | 00000110 | - |
+------+---------+----------+----------+-----------------------+
| 1 | 1111111 | 00101111 | 00000110 | RG2 := RG2 - RG1 |
| 1 | 1111111 | 01011110 | 00000110 | RG3 := l(RG3).!RG2[8] |
| | | | | RG2 := l(RG2).0 |
+------+---------+----------+----------+-----------------------+
| 2 | 1111111 | 01011000 | 00000110 | RG2 := RG2 - RG1 |
| 2 | 1111111 | 10110000 | 00000110 | RG3 := l(RG3).!RG2[8] |
| | | | | RG2 := l(RG2).0 |
+------+---------+----------+----------+-----------------------+
| 3 | 1111111 | 10110110 | 00000110 | RG2 := RG2 + RG1 |
| 3 | 1111110 | 01101100 | 00000110 | RG3 := l(RG3).!RG2[8] |
| | | | | RG2 := l(RG2).0 |
+------+---------+----------+----------+-----------------------+
| 4 | 1111110 | 01100110 | 00000110 | RG2 := RG2 - RG1 |
| 4 | 1111101 | 11001100 | 00000110 | RG3 := l(RG3).!RG2[8] |
| | | | | RG2 := l(RG2).0 |
+------+---------+----------+----------+-----------------------+
| 5 | 1111101 | 11010010 | 00000110 | RG2 := RG2 + RG1 |
| 5 | 1111010 | 10100100 | 00000110 | RG3 := l(RG3).!RG2[8] |
| | | | | RG2 := l(RG2).0 |
+------+---------+----------+----------+-----------------------+
| 6 | 1111010 | 10101010 | 00000110 | RG2 := RG2 + RG1 |
| 6 | 1110100 | 01010100 | 00000110 | RG3 := l(RG3).!RG2[8] |
| | | | | RG2 := l(RG2).0 |
+------+---------+----------+----------+-----------------------+
| 7 | 1110100 | 01001110 | 00000110 | RG2 := RG2 - RG1 |
| 7 | 1101001 | 10011100 | 00000110 | RG3 := l(RG3).!RG2[8] |
| | | | | RG2 := l(RG2).0 |
+------+---------+----------+----------+-----------------------+
| 8 | 1101001 | 10100010 | 00000110 | RG2 := RG2 + RG1 |
| 8 | 1010010 | 01000100 | 00000110 | RG3 := l(RG3).!RG2[8] |
| | | | | RG2 := l(RG2).0 |
+------+---------+----------+----------+-----------------------+
| 9 | 1010010 | 00111110 | 00000110 | RG2 := RG2 - RG1 |
| 9 | 0100101 | 01111100 | 00000110 | RG3 := l(RG3).!RG2[8] |
| | | | | RG2 := l(RG2).0 |
+------+---------+----------+----------+-----------------------+
Result: 100101
```
The results of the operations will be displayed, and you will get prompted for the next operation to perform. **Note** the results of previous operations don't impact the operands, therefore you can't plug your previous results into the calculator without restarting the program!
Also, as a quality of life feature, you can chain multiple operations in one prompt as such:
```
Choose the operation:
[a]ddition, [s]ubtraction, [m]ultiplication, [d]ivision, [q]uit
(110101 000110) > asm1d1
Sum: 111011
Carry: 0
Subtraction: 101111
Carry: 1
Multiplication (method 1):
+------+--------+--------+--------+-----+----------------------+
| iter | RG1 | RG2 | RG3 | CT | MicroOperations |
+------+--------+--------+--------+-----+----------------------+
| 0 | 000000 | 110101 | 000110 | 110 | - |
+------+--------+--------+--------+-----+----------------------+
| 1 | 000110 | 110101 | 000110 | 110 | RG1 := RG1 + RG3 |
| 1 | 000011 | 011010 | 000110 | 101 | RG2 := RG1[1].r(RG2) |
| | | | | | RG1 := 0.r(RG1) |
| | | | | | CT := CT - 1 |
+------+--------+--------+--------+-----+----------------------+
| 2 | 000001 | 101101 | 000110 | 100 | RG2 := RG1[1].r(RG2) |
| | | | | | RG1 := 0.r(RG1) |
| | | | | | CT := CT - 1 |
+------+--------+--------+--------+-----+----------------------+
| 3 | 000111 | 101101 | 000110 | 100 | RG1 := RG1 + RG3 |
| 3 | 000011 | 110110 | 000110 | 011 | RG2 := RG1[1].r(RG2) |
| | | | | | RG1 := 0.r(RG1) |
| | | | | | CT := CT - 1 |
+------+--------+--------+--------+-----+----------------------+
| 4 | 000001 | 111011 | 000110 | 010 | RG2 := RG1[1].r(RG2) |
| | | | | | RG1 := 0.r(RG1) |
| | | | | | CT := CT - 1 |
+------+--------+--------+--------+-----+----------------------+
| 5 | 000111 | 111011 | 000110 | 010 | RG1 := RG1 + RG3 |
| 5 | 000011 | 111101 | 000110 | 001 | RG2 := RG1[1].r(RG2) |
| | | | | | RG1 := 0.r(RG1) |
| | | | | | CT := CT - 1 |
+------+--------+--------+--------+-----+----------------------+
| 6 | 001001 | 111101 | 000110 | 001 | RG1 := RG1 + RG3 |
| 6 | 000100 | 111110 | 000110 | 000 | RG2 := RG1[1].r(RG2) |
| | | | | | RG1 := 0.r(RG1) |
| | | | | | CT := CT - 1 |
+------+--------+--------+--------+-----+----------------------+
Result: 000100111110
Division (method 1):
+------+---------+----------+----------+-----------------------+
| iter | RG3 | RG2 | RG1 | MicroOperations |
+------+---------+----------+----------+-----------------------+
| 0 | 1111111 | 00110101 | 00000110 | - |
+------+---------+----------+----------+-----------------------+
| 1 | 1111111 | 00101111 | 00000110 | RG2 := RG2 - RG1 |
| 1 | 1111111 | 01011110 | 00000110 | RG3 := l(RG3).!RG2[8] |
| | | | | RG2 := l(RG2).0 |
+------+---------+----------+----------+-----------------------+
| 2 | 1111111 | 01011000 | 00000110 | RG2 := RG2 - RG1 |
| 2 | 1111111 | 10110000 | 00000110 | RG3 := l(RG3).!RG2[8] |
| | | | | RG2 := l(RG2).0 |
+------+---------+----------+----------+-----------------------+
| 3 | 1111111 | 10110110 | 00000110 | RG2 := RG2 + RG1 |
| 3 | 1111110 | 01101100 | 00000110 | RG3 := l(RG3).!RG2[8] |
| | | | | RG2 := l(RG2).0 |
+------+---------+----------+----------+-----------------------+
| 4 | 1111110 | 01100110 | 00000110 | RG2 := RG2 - RG1 |
| 4 | 1111101 | 11001100 | 00000110 | RG3 := l(RG3).!RG2[8] |
| | | | | RG2 := l(RG2).0 |
+------+---------+----------+----------+-----------------------+
| 5 | 1111101 | 11010010 | 00000110 | RG2 := RG2 + RG1 |
| 5 | 1111010 | 10100100 | 00000110 | RG3 := l(RG3).!RG2[8] |
| | | | | RG2 := l(RG2).0 |
+------+---------+----------+----------+-----------------------+
| 6 | 1111010 | 10101010 | 00000110 | RG2 := RG2 + RG1 |
| 6 | 1110100 | 01010100 | 00000110 | RG3 := l(RG3).!RG2[8] |
| | | | | RG2 := l(RG2).0 |
+------+---------+----------+----------+-----------------------+
| 7 | 1110100 | 01001110 | 00000110 | RG2 := RG2 - RG1 |
| 7 | 1101001 | 10011100 | 00000110 | RG3 := l(RG3).!RG2[8] |
| | | | | RG2 := l(RG2).0 |
+------+---------+----------+----------+-----------------------+
| 8 | 1101001 | 10100010 | 00000110 | RG2 := RG2 + RG1 |
| 8 | 1010010 | 01000100 | 00000110 | RG3 := l(RG3).!RG2[8] |
| | | | | RG2 := l(RG2).0 |
+------+---------+----------+----------+-----------------------+
| 9 | 1010010 | 00111110 | 00000110 | RG2 := RG2 - RG1 |
| 9 | 0100101 | 01111100 | 00000110 | RG3 := l(RG3).!RG2[8] |
| | | | | RG2 := l(RG2).0 |
+------+---------+----------+----------+-----------------------+
Result: 100101
```
So that multiple operations are performed on the same operands without the need for multiple prompts.
+433 -44
View File
@@ -1,38 +1,107 @@
from collections import deque
from typing import Tuple, List, Any
from typing_extensions import Self
from prettytable import PrettyTable
class BasicRegister:
"""The BasicRegister represents a hardware register capable of manipulating multiple bits at a time.
"""
The BasicRegister represents a hardware register capable of manipulating multiple bits at a time.
:param deque[bool] memory: The bits stored inside the register.
"""
def __init__(self, memory: list[bool]):
"""Constructor method"""
self.memory: deque[bool] = deque(memory)
def __init__(self, memory: deque[bool]):
self.memory: deque[bool] = memory
def __repr__(self) -> str:
return "".join([str(int(value)) for value in self.memory])
def __str__(self) -> str:
return f"Memory: {[int(value) for value in self.memory]}"
return "".join([str(int(value)) for value in self.memory])
def reverse(self):
def __len__(self) -> int:
return len(self.memory)
def adjusted_by_size(self, resulting_size: int) -> Self:
"""
Adjusts a register to a given size.
:param int resulting_size: The size of the resulting register.
:return: A register of a specified size.
:rtype: BasicRegister
"""
current_memory_size: int = len(self.memory)
return BasicRegister(
deque([False] * max(resulting_size - current_memory_size, 0) + list(self.memory)[-resulting_size:])
)
def negate(self):
"""
Performs logical negation on the register.
"""
self.memory = deque([not value for value in self.memory])
def left_shift(self, digit_to_fill: bool = False, steps_shifted: int = 1) -> deque[bool]:
self.memory.extend([digit_to_fill] * steps_shifted)
shifted_radices: deque[bool] = deque([self.memory.popleft() for _i in range(steps_shifted)])
return shifted_radices
def left_shift(self, shift_in_value: bool = False, bits_shifted: int = 1) -> deque[bool]:
"""
Shifts the register to the left by a specified number of steps.
def right_shift(self, digit_to_fill: bool = False, steps_shifted: int = 1) -> deque[bool]:
self.memory.extendleft([digit_to_fill] * steps_shifted)
shifted_radices: deque[bool] = deque([self.memory.pop() for _i in range(steps_shifted)])
return shifted_radices
:param bool shift_in_value: The value that shifts inside the freed space.
:param int bits_shifted: The number of bits by which the register is shifted.
def adjust_size(self, s: int) -> None:
current_memory_size: int = len(self.memory)
return BasicRegister([False] * max(s - current_memory_size, 0) + list(self.memory)[-current_memory_size:])
:return: The bits shifted outside the register.
:rtype: deque[bool]
"""
self.memory.extend([shift_in_value] * bits_shifted)
shifted_bits: deque[bool] = deque([self.memory.popleft() for _i in range(bits_shifted)])
return shifted_bits
def right_shift(self, shift_in_value: bool = False, bits_shifted: int = 1) -> deque[bool]:
"""
Shifts the register to the right by a specified number of steps
:param bool shift_in_value: The value that shifts inside the freed space.
:param int bits_shifted: The number of bits by which the register is shifted.
:return: The bits shifted outside the register.
:rtype: deque[bool]
"""
self.memory.extendleft([shift_in_value] * bits_shifted)
shifted_bits: deque[bool] = deque([self.memory.pop() for _i in range(bits_shifted)])
return shifted_bits
def get_memory(variable_name: str) -> list[bool]:
class Counter(BasicRegister):
"""
The Counter represents a hardware register specifically designed for countdowns.
:param int value: Initial numeric value this Counter holds.
"""
def __init__(self, value: int):
# memory: deque[bool] = deque([i == "1" for i in bin(value)[2:]])
super().__init__(deque([i == "1" for i in bin(value)[2:]]))
# self.memory: deque[bool] = deque([i == "1" for i in bin(value)[2:]])
def __repr__(self) -> str:
return "".join([str(int(value)) for value in self.memory])
def __str__(self) -> str:
return "".join([str(int(value)) for value in self.memory])
def __len__(self) -> int:
return len(self.memory)
def decrement(self):
self.memory = binary_subtraction(self, BasicRegister(deque([False] * (len(self.memory) - 1) + [True]))).memory
def non_zero(self) -> bool:
return any(self.memory)
def get_memory(variable_name: str) -> deque[bool]:
"""
Reads user input to be used as a memory array.
@@ -45,42 +114,362 @@ def get_memory(variable_name: str) -> list[bool]:
input_chars: list[str] = list(input(f"Enter {variable_name}: "))
if all(character in ["0", "1"] for character in input_chars):
return [True if character == "1" else False for character in input_chars]
return deque([True if character == "1" else False for character in input_chars])
else:
print(f"[ERROR] The {variable_name} may contain only 1-s and 0-s!")
def sum(a_original: BasicRegister, b_original: BasicRegister) -> BasicRegister:
def binary_sum_with_carry(first_term: BasicRegister, second_term: BasicRegister) -> tuple[BasicRegister, int]:
"""
Sums two registers' values.
Sums two registers' values and keeps the carry-out.
:param BasicRegister a: First register.
:param BasicRegister b: Second register.
:param BasicRegister first_term: First register.
:param BasicRegister second_term: Second register.
:return: Register containing the result.
:rtype: BasicRegister
:return: Register containing the sum and the carry-out bit.
:rtype: tuple[BasicRegister, int]
"""
size_a = len(a_original.memory)
size_b = len(b_original.memory)
required_size = max(size_a, size_b)
if size_a != size_b:
a = a_original.adjust_size(required_size)
b = b_original.adjust_size(required_size)
else:
a = a_original
b = b_original
c = BasicRegister([False] * required_size)
result_term = BasicRegister(deque([False] * len(first_term)))
carry = False
for i in range(size_a - 1, 0, -1):
current_bit_sum = a.memory[i] + b.memory[i] + carry
for i in range(len(first_term) - 1, -1, -1):
current_bit_sum = first_term.memory[i] + second_term.memory[i] + carry
carry = bool(current_bit_sum & 2)
c.memory[i] = bool(current_bit_sum & 1)
result_term.memory[i] = bool(current_bit_sum & 1)
final_bit_sum = a.memory[0] + b.memory[0] + carry
c.memory[0] = bool(final_bit_sum & 1)
return result_term, carry
return c
def binary_sum(first_term: BasicRegister, second_term: BasicRegister) -> BasicRegister:
"""
Sums two terms containing binary numbers.
:param BasicRegister first_term: First register to add.
:param BasicRegister second_term: Second register to add.
:return: Register containing the sum.
:rtype: BasicRegister
"""
return binary_sum_with_carry(first_term, second_term)[0]
def binary_subtraction(minuend: BasicRegister, subtrahend: BasicRegister) -> BasicRegister:
"""
Subtracts the second term from the first in binary using ones' complement.
:param BasicRegister minuend: Register to subtract from.
:param BasicRegister subtrahend: Register to subtract by.
:return: Register containing the difference.
:rtype: BasicRegister
"""
subtrahend = BasicRegister(subtrahend.memory)
subtrahend.negate()
difference: BasicRegister
final_carry: bool
difference, final_carry = binary_sum_with_carry(minuend, subtrahend)
if final_carry:
return binary_sum(difference, BasicRegister(deque([False] * (len(difference) - 1) + [True])))
else:
difference.negate()
return difference
def binary_subtraction_second_complement(minuend: BasicRegister, subtrahend: BasicRegister) \
-> tuple[BasicRegister, bool]:
"""
Subtracts the second term from the first in binary using seconds' complement.
:param BasicRegister minuend: Register to subtract from.
:param BasicRegister subtrahend: Register to subtract by.
:return: Register containing the difference.
:rtype: BasicRegister
"""
subtrahend = BasicRegister(subtrahend.memory)
subtrahend.negate()
subtrahend = binary_sum(*align_registers(subtrahend, BasicRegister([True])))
difference: BasicRegister
final_carry: bool
difference, final_carry = binary_sum_with_carry(minuend, subtrahend)
return difference, final_carry
def align_registers(*registers: BasicRegister) -> tuple[BasicRegister, ...]:
"""
Aligns registers by the length of the bigger one.
:param BasicRegister registers: Registers to align.
:return: Aligned registers.
:rtype: tuple[BasicRegister, ...]
"""
required_size: int = max(map(len, registers))
return tuple(reg.adjusted_by_size(required_size) for reg in registers)
def format_device_state_table(table) -> str:
pt = PrettyTable()
pt.field_names = table[0]
for block in table[1:]:
for line in block[:-1]:
pt.add_row(line)
pt.add_row(block[-1], divider=True)
return pt.get_string()
def binary_multiplication_method_1(first_term: BasicRegister, second_term: BasicRegister) \
-> tuple[BasicRegister, list[list[str]]]:
"""
Multiplies two terms containing binary numbers using first method.
:param BasicRegister first_term: First register to multiply.
:param BasicRegister second_term: Second register to multiply.
:return: Register containing the product.
:rtype: BasicRegister
"""
first_term, second_term = align_registers(first_term, second_term)
n: int = len(first_term)
rg1 = BasicRegister(deque([False] * n))
rg2 = BasicRegister(first_term.memory)
rg3 = BasicRegister(second_term.memory)
ct = Counter(n)
data_table = [["iter", "RG1", "RG2", "RG3", "CT", "MicroOperations"]]
i = 0
data_table.append([])
data_table[-1].append(list(map(str, [i, rg1, rg2, rg3, ct, "-"])))
while ct.non_zero():
i += 1
data_table.append([])
if rg2.memory[n-1]:
rg1 = binary_sum(rg1, rg3)
data_table[-1].append(list(map(str, [i, rg1, rg2, rg3, ct, "RG1 := RG1 + RG3"])))
rg2.right_shift(rg1.memory[n-1])
rg1.right_shift()
ct.decrement()
data_table[-1].append(list(map(str, [i, rg1, rg2, rg3, ct, "RG2 := RG1[1].r(RG2)\nRG1 := 0.r(RG1)\nCT := CT - 1"])))
return BasicRegister(rg1.memory + rg2.memory), data_table
def binary_multiplication_method_2(first_term: BasicRegister, second_term: BasicRegister) \
-> tuple[BasicRegister, list[list[str]]]:
"""
Multiplies two terms containing binary numbers using second method.
:param BasicRegister first_term: First register to multiply.
:param BasicRegister second_term: Second register to multiply.
:return: Register containing the product.
:rtype: BasicRegister
"""
first_term, second_term = align_registers(first_term, second_term)
n: int = len(first_term)
rg1 = BasicRegister(deque([False] * (2*n)))
rg2 = BasicRegister(first_term.memory)
rg3 = BasicRegister(deque([False] * n + list(second_term.memory)))
i = 0
data_table = [["iter", "RG1", "RG2", "RG3", "MicroOperations"], []]
data_table[-1].append(list(map(str, [i, rg1, rg2, rg3, "-"])))
while any(rg2.memory):
i += 1
data_table.append([])
if rg2.memory[n-1]:
rg1 = binary_sum(rg1, rg3)
data_table[-1].append(list(map(str, [i, rg1, rg2, rg3, "RG1 := RG1 + RG3"])))
rg2.right_shift()
rg3.left_shift()
data_table[-1].append(list(map(str, [i, rg1, rg2, rg3, "RG2 := 0.r(RG2)\nRG3 := l(RG3).0"])))
return rg1, data_table
def binary_multiplication_method_3(first_term: BasicRegister, second_term: BasicRegister) \
-> tuple[BasicRegister, list[list[str]]]:
"""
Multiplies two terms containing binary numbers using third method.
:param BasicRegister first_term: First register to multiply.
:param BasicRegister second_term: Second register to multiply.
:return: Register containing the product.
:rtype: BasicRegister
"""
first_term, second_term = align_registers(first_term, second_term)
n: int = len(first_term)
data_table = [["iter", "RG2", "RG1", "RG3", "CT", "MicroOperations"]]
rg1 = BasicRegister(deque([False] * n))
rg2 = BasicRegister(first_term.memory + deque([False]))
rg3 = BasicRegister(deque([False] * (n+1)) + second_term.memory)
ct = Counter(n)
i = 0
data_table.append([])
data_table[-1].append(list(map(str, [i, rg2, rg1, rg3, ct, "-"])))
while ct.non_zero():
i += 1
data_table.append([])
if rg2.memory[0]:
result: list[bool] = list(binary_sum(BasicRegister(rg2.memory + rg1.memory), rg3).memory)
rg2 = BasicRegister(deque(result[:n+1]))
rg1 = BasicRegister(deque(result[n+1:]))
data_table[-1].append(list(map(str, [i, rg2, rg1, rg3, ct, "RG2.RG1 := RG2.RG1 + RG3"])))
rg2.left_shift(rg1.memory[0])
rg1.left_shift()
ct.decrement()
data_table[-1].append(list(map(str, [i, rg2, rg1, rg3, ct, "RG2.RG1 := l(RG2.RG1).0\nCT := CT - 1"])))
return BasicRegister(deque(list(rg2.memory + rg1.memory)[:-1])), data_table
def binary_multiplication_method_4(first_term: BasicRegister, second_term: BasicRegister) \
-> tuple[BasicRegister, list[list[str]]]:
"""
Multiplies two terms containing binary numbers using fourth method.
:param BasicRegister first_term: First register to multiply.
:param BasicRegister second_term: Second register to multiply.
:return: Register containing the product.
:rtype: BasicRegister
"""
first_term, second_term = align_registers(first_term, second_term)
n: int = len(first_term)
rg1 = BasicRegister(deque([False] * (2*n+1)))
rg2 = BasicRegister(first_term.memory)
rg3 = BasicRegister(deque([False]) + second_term.memory + deque([False] * n))
data_table = [["iter", "RG1", "RG2", "RG3", "MicroOperations"]]
i = 0
data_table.append([])
data_table[-1].append(list(map(str, [i, rg1, rg2, rg3, "-"])))
while any(rg2.memory):
i += 1
data_table.append([])
if rg2.memory[0]:
rg1 = binary_sum(rg1, rg3)
data_table[-1].append(list(map(str, [i, rg1, rg2, rg3, "RG1 := RG1 + RG3"])))
rg2.left_shift()
rg3.right_shift()
data_table[-1].append(list(map(str, [i, rg1, rg2, rg3, "RG2 := l(RG2).0\nRG3 := 0.r(RG3)"])))
return BasicRegister(deque(list(rg1.memory)[:-1])), data_table
def binary_division_method_1(first_term: BasicRegister, second_term: BasicRegister) \
-> tuple[BasicRegister, list[list[str]]]:
"""
Divides first term by the second term containing binary numbers using first method.
:param: BasicRegister first_term: Register being divided.
:param: BasicRegister second_term: Register being divided by.
:return: Register containing the division result.
:rtype: BasicRegister
"""
first_term, second_term = align_registers(first_term, second_term)
n: int = len(first_term)
rg1 = BasicRegister(deque([False, False]) + second_term.memory)
rg2 = BasicRegister(deque([False, False]) + first_term.memory)
rg3 = BasicRegister(deque([True] * (n+1)))
data_table = [["iter", "RG3", "RG2", "RG1", "MicroOperations"]]
i = 0
data_table.append([])
data_table[-1].append(list(map(str, [i, rg3, rg2, rg1, "-"])))
while rg3.memory[0]:
i += 1
data_table.append([])
if rg2.memory[0]:
rg2 = binary_sum(rg2, rg1)
data_table[-1].append(list(map(str, [i, rg3, rg2, rg1, "RG2 := RG2 + RG1"])))
else:
rg2, _ = binary_subtraction_second_complement(rg2, rg1)
data_table[-1].append(list(map(str, [i, rg3, rg2, rg1, "RG2 := RG2 - RG1"])))
rg3.left_shift(not rg2.memory[0])
rg2.left_shift()
data_table[-1].append(list(map(str, [i, rg3, rg2, rg1, f"RG3 := l(RG3).!RG2[{n+2}]\nRG2 := l(RG2).0"])))
return BasicRegister(deque(list(rg3.memory)[1:])), data_table
def binary_division_method_2(first_term: BasicRegister, second_term: BasicRegister) \
-> tuple[BasicRegister, list[list[str]]]:
"""
Divides first term by the second term containing binary numbers using second method.
:param: BasicRegister first_term: Register being divided.
:param: BasicRegister second_term: Register being divided by.
:return: Register containing the division result.
:rtype: BasicRegister
"""
first_term, second_term = align_registers(first_term, second_term)
n: int = len(first_term)
rg1 = BasicRegister(deque([False]) + second_term.memory + deque([False]*n))
rg2 = BasicRegister(deque([False]) + first_term.memory + deque([False]*n))
rg3 = BasicRegister(deque([True] * (n+1)))
data_table = [["iter", "RG3", "RG2", "RG1", "MicroOperations"]]
i = 0
carry = False
data_table.append([])
data_table[-1].append(list(map(str, [i, rg3, rg2, rg1, "-"])))
while rg3.memory[0]:
i += 1
data_table.append([])
if rg2.memory[0]:
rg2, carry = binary_sum_with_carry(rg2, rg1)
data_table[-1].append(list(map(str, [i, rg3, rg2, rg1, "RG2 := RG2 + RG1"])))
else:
rg2, carry = binary_subtraction_second_complement(rg2, rg1)
data_table[-1].append(list(map(str, [i, rg3, rg2, rg1, "RG2 := RG2 - RG1"])))
rg3.left_shift(carry)
rg1.right_shift()
data_table[-1].append(list(map(str, [i, rg3, rg2, rg1, f"RG3 := l(RG3).SM[p]\nRG1 := 0.r(RG1)"])))
return BasicRegister(deque(list(rg3.memory)[1:])), data_table
+114 -23
View File
@@ -1,28 +1,119 @@
from bitutilities import *
import timeit
import bitutilities as bu
operation = ""
method = ""
user_input = []
def process_command(symbol):
global operation, method
if symbol.lower() in "asmdq":
operation = symbol
elif operation == "m" and symbol in "1234":
method = symbol
elif operation == "d" and symbol in "12":
method = symbol
elif symbol in " ;:":
pass
else:
print(f"Error: unexpected instruction '{symbol}', skipping")
def perform_operation(first_register: bu.BasicRegister, second_register: bu.BasicRegister):
global operation, method
match operation:
case "a":
result, carry = bu.binary_sum_with_carry(first_register, second_register)
print(f"\nSum: {result}\nCarry: {int(carry)}")
operation, method = "", ""
case "s":
result, carry = bu.binary_subtraction_second_complement(first_register, second_register)
print(f"\nSubtraction: {result}\nCarry: {int(carry)}")
operation, method = "", ""
case "m":
match method:
case "1":
result, data_table = bu.binary_multiplication_method_1(first_register, second_register)
print(f"\nMultiplication (method 1):\n{bu.format_device_state_table(data_table)}\nResult: {result}")
operation, method = "", ""
case "2":
result, data_table = bu.binary_multiplication_method_2(first_register, second_register)
print(f"\nMultiplication (method 2):\n{bu.format_device_state_table(data_table)}\nResult: {result}")
operation, method = "", ""
case "3":
result, data_table = bu.binary_multiplication_method_3(first_register, second_register)
print(f"\nMultiplication (method 3):\n{bu.format_device_state_table(data_table)}\nResult: {result}")
operation, method = "", ""
case "4":
result, data_table = bu.binary_multiplication_method_4(first_register, second_register)
print(f"\nMultiplication (method 4):\n{bu.format_device_state_table(data_table)}\nResult: {result}")
operation, method = "", ""
case _:
pass
case "d":
match method:
case "1":
result, data_table = bu.binary_division_method_1(first_register, second_register)
print(f"\nDivision (method 1):\n{bu.format_device_state_table(data_table)}\nResult: {result}")
operation, method = "", ""
case "2":
result, data_table = bu.binary_division_method_2(first_register, second_register)
print(f"\nDivision (method 2):\n{bu.format_device_state_table(data_table)}\nResult: {result}")
operation, method = "", ""
case _:
pass
case "q":
exit(0)
case _:
pass
def get_prompt_text(operation: any, method: any) -> str:
response = "({} {})"
if operation:
response += " {}"
if operation and method:
response += "/{}"
return response
def input_handler(first_register: bu.BasicRegister, second_register: bu.BasicRegister):
global user_input, operation
first_register, second_register = bu.align_registers(first_register, second_register)
print()
print(first_register)
print(second_register)
while True:
prompt_text: str = get_prompt_text(operation, method).format(first_register, second_register, operation, method)
print()
if operation == "":
raw_user_input = input("Choose the operation:\n"
"[a]ddition, [s]ubtraction, [m]ultiplication, [d]ivision, [q]uit\n" +
prompt_text + " > ")
elif operation == "m":
raw_user_input = input("Choose method to use (1-4):\n" + prompt_text + " > ")
elif operation == "d":
raw_user_input = input("Choose method to use (1-2):\n" + prompt_text + " > ")
user_input = list(raw_user_input)
for symbol in user_input:
process_command(symbol)
perform_operation(first_register, second_register)
if __name__ == '__main__':
reg: BasicRegister = BasicRegister(get_memory("memory"))
# print(type(reg))
reg1: bu.BasicRegister = bu.BasicRegister(bu.get_memory("first operand"))
reg2: bu.BasicRegister = bu.BasicRegister(bu.get_memory("second operand"))
print("\nRegister:")
print(reg)
# TODO live-swapping of registers!!!
print("\nReversed:")
reg.reverse()
print(reg)
print("\nShifted left:")
print([int(value) for value in reg.left_shift()])
print(reg)
print("\nShifted right:")
print([int(value) for value in reg.right_shift()])
print(reg)
reg2: BasicRegister = BasicRegister(get_memory("more memory"))
reg3: BasicRegister = sum(reg, reg2)
print(reg3)
input_handler(reg1, reg2)