Code: Select all
>>> import struct; bits=[0,0,0,1,0,0,0,0,1,0,0,0]; bytes=b''
>>> for i in range(0,len(bits),8): den=int("".join(map(str, bits[i:i+8])), 2); bytes+=struct.pack('b',den); print(bytes)
...
b'\x10'
b'\x10\x08'
Code: Select all
>>> import struct; bits=[0,0,0,1,0,0,0,0,1,0,0,0]; bytes=b''
>>> for i in range(0,len(bits),8): den=int("".join(map(str, bits[i:i+8])), 2); bytes+=struct.pack('b',den); print(bytes)
...
b'\x10'
b'\x10\x08'
Code: Select all
>>> struct.pack('<H', sum(b*(1<<(i^7)) for i, b in enumerate(bits)))
b'\x10\x80'
Code: Select all
>>> bits=[0,0,0,1,0,0,0,0,1,0,0,0]
>>> struct.pack('<H', sum(b*(1<<(i^7)) for i, b in enumerate(bits)))
b'\x10\x80'
>>> struct.pack('<H', sum(b*(1<<(i)) for i, b in enumerate(bits)))
b'\x08\x01'
Code: Select all
>> bits=[0,0,1,0,0,0,0,0,1,0,0,0]
>>> struct.pack('<H', sum(b*(1<<(i^7)) for i, b in enumerate(bits)))
b' \x80'
>>> struct.pack('<H', sum(b*(1<<(i)) for i, b in enumerate(bits)))
b'\x04\x01'
No, but you can use
Code: Select all
>>> import binascii
>>> binascii.hexlify(b' \x80', ' ')
b'20 80'
Python's rules for printing bytes (or bytearrays) is to show the character if it's printable, otherwise the escape sequence. The actual data is correct though, and if you send it over the network (e.g. LoRa) then it will be fine.
Maybe this will help you.
Code: Select all
>>> b=bytes((0x08, 0x50, 0xf0,))
>>> print(b)
b'\x08P\xf0'
>>> import binascii
>>> print(f'0x{binascii.hexlify(b).decode()}')
0x0850f0
>>> print(list(i for i in b))
[8, 80, 240]
>>> print(list(hex(i) for i in b))
['0x8', '0x50', '0xf0']
Yes I mean escape characters -- in Python (like C, Java, etc), the backslash is the escape character. It indicates the start of a sequence to let you tell the compiler exactly what character you want -- useful if that character isn't printable. So for example \n for newline (which is the byte value 10 in decimal, or 0x0a in hex).