-
Notifications
You must be signed in to change notification settings - Fork 0
/
binarybuffer.py
56 lines (44 loc) · 1.48 KB
/
binarybuffer.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
# Copyright 2021 Seeky
# Licensed under GPLv2+
class BinaryBuffer:
def __init__(self, data):
self.data = bytearray(data[:])
def writeat(self, offset, data):
for i, val in enumerate(data):
self.data[offset+i] = val
def readat(self, offset, length):
out = bytearray()
for i in range(0, length):
out.append(self.data[offset+i])
return out
def writeWord(self, offset, val):
b = int.to_bytes(val, 4, 'big')
self.writeat(offset, b)
def writeHalfword(self, offset, val):
b = int.to_bytes(val, 2, 'big')
self.writeat(offset, b)
def writeByte(self, offset, val):
b = int.to_bytes(val, 1, 'big')
self.writeat(offset, b)
def writeStr(self, offset, str):
i = 0
for c in str:
self.data[offset+i] = ord(c)
i += 1
self.data[offset+i] = 0
def readWord(self, offset):
return int.from_bytes(self.readat(offset, 4), 'big')
def readHalfword(self, offset):
return int.from_bytes(self.readat(offset, 2), 'big')
def readByte(self, offset):
return int.from_bytes(self.readat(offset, 1), 'big')
def readStr(self, offset, encoding='ascii'):
out = bytearray()
i = 0
while True:
c = self.data[offset+i]
if c == 0:
break
i += 1
out.append(c)
return out.decode(encoding=encoding)