Fixed length Python package

I am trying to create a fixed length package in python for a PSIP ATSC generator. It's probably very simple, but so far I can't get it to work. I am trying to create a package with fields like the following:

table_id = 0xCB
syntax = 0b1
reserved = 0b11
table_ext = 0xFF

      

the end goal will be the following in binary

'1100101111111111111'

      

I've tried a dozen different things and can't get the expected results. I'm going to send this over sockets, so I believe it should be in a string.

+2


source to share


2 answers


You can use struct

module
to create binary strings from arbitrary layouts.

This can only generate byte-aligned structures, but you have to be byte-aligned to send on a network socket.

EDIT:

So the format you are generating does indeed have inconsistent bits 8-1-1-2-12-16, etc.



To send to a socket, you must be byte-aligned, but I think the protocol handles some of that. (maybe with bits somewhere?)

My new suggestion was to create a bit string and then cut it into 8-bit blocks and convert from it:

input_binary_string = "110010111111111111101010" ## must be a multiple of 8
out = []
while len(input_binary_string) >= 8:
    byte = input_binary_string[:8]
    input_binary_string = input_binary_string[8:]
    b = int(byte,2)
    c = chr(b)
    out.append(c)
## Better not have a bits left over
assert len(input_binary_string) == 0
outString = "".join(out)

print [ ord(c) for c in out ]

      

+4


source


Construct ( http://construct.readthedocs.org/en/latest/ ) is a parser and builder for binary data. It is really perfect for this application as you can define things from bits and bytes. It also has useful features such as conditional handling as well as the ability to easily check for terminators and the like.



I've spent years using a system for complex packaging and parsing that lacked some of the functionality that Construct has, so unless there is anything particularly odd about the protocol, it looks like Construct will handle it.

0


source







All Articles