Last active
August 8, 2024 19:19
-
-
Save CodeByAidan/2575ce2bd31c02e238d19c2d20a96e97 to your computer and use it in GitHub Desktop.
Int to Byte (big endian) State Machine, in Python, type annotated.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class StateMachine: | |
def __init__(self, value: int) -> None: | |
self.value: int = value | |
self.state = "START" | |
self.byte_list: list[int] = [] | |
def run(self) -> bytes: | |
while self.state != "END": | |
self.transition() | |
return bytes(self.byte_list[::-1]) | |
def transition(self) -> None: | |
if self.state == "START": | |
if self.value == 0: | |
self.state = "END" | |
else: | |
self.byte_list.append(self.value & 0xFF) | |
self.value >>= 8 | |
self.state = "RUNNING" | |
elif self.state == "RUNNING": | |
if self.value == 0: | |
self.state = "END" | |
else: | |
self.byte_list.append(self.value & 0xFF) | |
self.value >>= 8 | |
sm = StateMachine(1024) | |
byte_data: bytes = sm.run() | |
print(byte_data) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment