Commit int packer with dbg to keep it in history
Results match expectation
This commit is contained in:
parent
dd888341d3
commit
10c089debc
45
twnet_parser/packer.py
Normal file
45
twnet_parser/packer.py
Normal file
|
@ -0,0 +1,45 @@
|
|||
#!/usr/bin/env python
|
||||
|
||||
from textwrap import wrap
|
||||
|
||||
def dbg(raw: bytearray) -> None:
|
||||
bits_str = ''
|
||||
annotation_str = ''
|
||||
for byte in raw:
|
||||
bits_str += ' '.join(wrap(f"{byte:08b} ", 2))
|
||||
annotation_str += 'ES DD DD DD '
|
||||
print(f" {bits_str} {bytes(raw)!r}")
|
||||
print(f" {annotation_str}")
|
||||
|
||||
def pack_int(num: int) -> bytes:
|
||||
print(f"packing {num}")
|
||||
res: bytearray = bytearray(b'\x00')
|
||||
if num < 0:
|
||||
res[0] |= 0x40 # set sign bit
|
||||
print(f"num={num}")
|
||||
num = ~num
|
||||
# print(f"num num={num}")
|
||||
|
||||
# print("--- signed:")
|
||||
# dbg(res)
|
||||
|
||||
res[0] |= num & 0x3F # pack 6bit into res
|
||||
num >>= 6 # discard 6 bits
|
||||
|
||||
print("--- pack 6 bit:")
|
||||
dbg(res)
|
||||
|
||||
i = 0
|
||||
while num != 0:
|
||||
res[i] |= 0x80 # set extend bit
|
||||
i += 1
|
||||
res.extend(bytes([num & 0x7F])) # pack 7 bit
|
||||
num >>= 7 # discard 7 bits
|
||||
print(num)
|
||||
|
||||
return bytes(res)
|
||||
|
||||
print(pack_int(63))
|
||||
print(pack_int(64))
|
||||
print(pack_int(65))
|
||||
|
Loading…
Reference in a new issue