Added files
This commit is contained in:
78
dane/game/debug/arrajki/am_array_encoder.py
Normal file
78
dane/game/debug/arrajki/am_array_encoder.py
Normal file
@@ -0,0 +1,78 @@
|
||||
data_to_encode = [
|
||||
"Test",
|
||||
True,
|
||||
1.5,
|
||||
1,
|
||||
"TRUE",
|
||||
False,
|
||||
0.0,
|
||||
0
|
||||
]
|
||||
|
||||
def intToBytes(i):
|
||||
return i.to_bytes(4, byteorder="little", signed=True)
|
||||
|
||||
def bytesToInt(b):
|
||||
return int.from_bytes(b, byteorder="little", signed=True)
|
||||
|
||||
def encode(data):
|
||||
encoded_bytes = b""
|
||||
|
||||
encoded_bytes += intToBytes(len(data))
|
||||
|
||||
for d in data:
|
||||
if type(d) == int:
|
||||
encoded_bytes += intToBytes(1)
|
||||
encoded_bytes += intToBytes(d)
|
||||
elif type(d) == float:
|
||||
encoded_bytes += intToBytes(4)
|
||||
encoded_bytes += intToBytes(int(d*10000))
|
||||
elif type(d) == str:
|
||||
encoded_bytes += intToBytes(2)
|
||||
encoded_bytes += intToBytes(len(d))
|
||||
encoded_bytes += d.encode("utf-8")
|
||||
elif type(d) == bool:
|
||||
encoded_bytes += intToBytes(3)
|
||||
encoded_bytes += intToBytes(int(d))
|
||||
|
||||
print(encoded_bytes)
|
||||
return encoded_bytes
|
||||
|
||||
def decode(encoded_bytes):
|
||||
data = []
|
||||
bytes_read = 0
|
||||
|
||||
array_length = bytesToInt(encoded_bytes[bytes_read:bytes_read+4])
|
||||
bytes_read += 4
|
||||
|
||||
for _ in range(array_length):
|
||||
data_type = bytesToInt(encoded_bytes[bytes_read:bytes_read+4])
|
||||
bytes_read += 4
|
||||
|
||||
if data_type == 1:
|
||||
data.append(bytesToInt(encoded_bytes[bytes_read:bytes_read+4]))
|
||||
bytes_read += 4
|
||||
elif data_type == 4:
|
||||
data.append(bytesToInt(encoded_bytes[bytes_read:bytes_read+4])/10000)
|
||||
bytes_read += 4
|
||||
elif data_type == 2:
|
||||
string_length = bytesToInt(encoded_bytes[bytes_read:bytes_read+4])
|
||||
bytes_read += 4
|
||||
data.append(encoded_bytes[bytes_read:bytes_read+string_length].decode("utf-8"))
|
||||
bytes_read += string_length
|
||||
elif data_type == 3:
|
||||
data.append(bool(bytesToInt(encoded_bytes[bytes_read:bytes_read+4])))
|
||||
bytes_read += 4
|
||||
else:
|
||||
raise ValueError("Unknown data type")
|
||||
|
||||
return data
|
||||
|
||||
with open("testowe_dane.arr", "wb") as f:
|
||||
f.write(encode(data_to_encode))
|
||||
|
||||
#with open("testowe_dane_mixed.arr", "rb") as f:
|
||||
# print(decode(f.read()))
|
||||
|
||||
#with open("TESTOWE_DANE_ZMIANY.ARR", "rb") as f:
|
||||
# print(decode(f.read()))
|
||||
Reference in New Issue
Block a user