title: Octet (byte) stuffing and unstuffing, i.e. replacing one byte with two or v.v
body: <p>I am receiving binary data from a device, via a socket (bluetooth), using socket.recv().</p>
  
  <p>I've considered buffering in a list or bytearray until sufficient data has been received to be decoded and acted upon. That is, until I've received a start- and a stop flag (bytes).</p>
  
  <p>However, the device is applying "octet stuffing". That is, every occurrence of the following two bytes should be replaced with a single byte, like so:</p>
  
  <pre><code>dic = { '\xFE\xDC' : '\xFC' , '\xFE\xDD' : '\xFD' , '\xFE\xDE' : '\xFE'}
  </code></pre>
  
  <p>In addition, when data is being sent, the reverse should be applied. For instance, one byte 0xFC -> yields two bytes 0xFE, 0xDC.</p>
  
  <p>What really happens is that when stuffing (sending data) if one of 0xFC, 0xFD, 0xFE is detected, 0xFE is added ahead of the byte, which is itself XORed 0x20. On unstuffing (receiving data) the 0XFE is discarded and the following byte is XORed 0x20. </p>
  
  <p>To say I'm fairly new to Python would be an understatement. I've started coding yesterday, have an interface up and running. This however, is kind of tricky.</p>
  
  <p>I know I can put the data into a string and do a replace. But to pack binary data into a string, replace and then unpack and decode seems a bit inefficient.</p>
  
  <p>I can also watch incoming data and act when I see the 0xFE flag. What would be nice is a way to stuff/unstuff a list, bytearray or whatever.</p>
  
  <p>Replacing single bytes in a list or bytearray doesn't seem too hard, but replacing one with two or the other way around ...?</p>
  
  <p>Any help very much appreciated.</p>
  
  <p>(This is Python 2.7 by the way.)</p>