Advertisement
Guest User

Untitled

a guest
Sep 19th, 2019
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.23 KB | None | 0 0
  1. I'm debugging a code written by another developer. I have a bitstream of data of different sizes which is written to a binary file as follows:
  2.  
  3. bitstream.add(0x01, 8)
  4. bitstream.add(0x01, 32) # write data unit dummy size
  5.  
  6. par_id, ps_id = 16
  7. bitstream.add(par_id, 12)
  8. bitstream.add(ps_id, 12)
  9.  
  10. where the `add` function is the following:
  11.  
  12. def add(self, data, length):
  13. s = ''
  14. if (type(data) == str):
  15. for char in data:
  16. b = bin(ord(char))[2:]
  17. s = s + "{:0>8}".format(b)
  18. else:
  19. s = bin(data)[2:]
  20. if (len(s) < length):
  21. resto = length - len(s)
  22. for _ in range(0, resto):
  23. s = '0' + s
  24.  
  25. s = s[0:length]
  26.  
  27. self.cache = self.cache + s
  28. self.flush()
  29.  
  30. The bitstream then contains
  31.  
  32. - 8 bits -> value 0x01
  33. - 32 bits -> value 0x01
  34. - 12 bits -> value 16
  35. - 12 bits -> value 16
  36.  
  37. I have some issues in decoding the bitstream
  38.  
  39. # unpack first 1 byte/8 bits
  40. data1, = struct.unpack('>B', in_file.read(1)) # value 1
  41.  
  42. # unpack 2 bytes/16 bits
  43. number_tmp = struct.unpack('>H', in_file.read(2))[0] # value 16
  44.  
  45. # set the 16th bit in number_tmp
  46. data2 = (data1 << 16) | number_tmp # value 65552
  47.  
  48. # get last 5 bits in data2
  49. ps.parent_id = data2 >> 12 # value 16
  50.  
  51. # bit mask 12 bits
  52. ps.id = data2 & 0x000FFF # value 16
  53.  
  54. What it is not clear to me:
  55.  
  56. 1. **data1** contains the first 8 bits and its value is 1 **OK**
  57. 2. **number_tmp** contains the following 16 bits, but its value is not 1 **NOT OK**
  58.  
  59. **OBS**: I'm expecting to read the next 32 bits of the bitstream flow described above, instead it appears these 32 bits are ignored, since `number_tmp` evaluates to 16.
  60.  
  61.  
  62. 3. **data2** is needed to set the 16th bit of `number_tmp`. I'm totally new to this kind of operations, so it is not really clear what is the purpose.
  63. 4. **ps.parent_id** is set to the decimal value of the last 5 bits of `data2`
  64. 5. **ps.id** is set to the decimal value of the first 5 bits of `data2`
  65.  
  66. Could anyone put light in my issues? I've read some tutorial but I could not find a proper explanation of what happens in my code.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement