Most pythonic way to implement byte stuffing algorithm

Travis Griggs travisgriggs at
Tue Apr 17 14:37:15 EDT 2018

> On Apr 17, 2018, at 11:15 AM, MRAB <python at> wrote:
> On 2018-04-17 17:02, Travis Griggs wrote:
>> I posted this on SO, but… yeah…
>> I'm doing some serial protocol stuff and want to implement a basic byte stuffing algorithm in python. Though really what this really generalizes to is “what is the most pythonic way to transform one sequence of bytes where some bytes are passed through 1:1, but others are transformed to longer subsequences of bytes?” I’m pretty sure this rules out the use of transform() which expects a 1:1 mapping.
> [snip]
> There are only 256 possible input bytes, so just put them into a dict and look them up.
> -- 

So something like this?

LUT = list(bytes([x]) for x in range(256))
LUT[PacketCode.Escape] = bytes([PacketCode.Escape, PacketCode.Escape ^ 0xFF])
LUT[PacketCode.Start] = bytes([PacketCode.Escape, PacketCode.Start ^ 0xFF])
LUT[PacketCode.Stop] = bytes([PacketCode.Escape, PacketCode.Stop ^ 0xFF])
def stuff6(bits):
   return b''.join(LUT[x] for x in bits)

More information about the Python-list mailing list