binary and structures

Very nice way to handle binary data

Create a named structure

Calculate the Data Mask for the data line

unpack into _make

Example Code

from struct import *
from collections import namedtuple
import pprint
phone_bill_rec=namedtuple("phone_bill",'message_id receipt_time phone_bill_type origin destination cp_client_id sequence spu spu_mrn mo_mrn phone_bill_status mo_msc_msisdn cos_num1 cos_num2 protocol_id data_coding message_header message_length message eor')

ifp=open('data','rb')
#Line should 231 Bytes
line=ifp.readline()

#Unpack using a structure definition
#I think the fields sizes are like this
#4,4,1,20,20,1,4,1,4,1,1,20,1,1,1,1,1,1,160,4
#i is 4 bytes Integer
#b is 1 byte Integer
#20s is 20bytes bytes

s=sms_rec._make(unpack('iib20s20sbibibi20sbbbbbb129s4s',line))

Format codes

Format C Type Python Type Size Standard note
x pad byte no value
c char bytes of length 1 1
b signed char integer 1 (1),(3)
B unsigned char integer 1 (3)
? _Bool bool 1 (1)
h short integer 2 (3)
H unsigned short integer 2 (3)
i int integer 4 (3)
I unsigned int integer 4 (3)
l long integer 4 (3)
L unsigned long integer 4 (3)
q long long integer 8 (2), (3)
Q unsigned long long integer 8 (2), (3)
n ssize_t integer (4)
N size_t integer (4)
f float float 4 (5)
d double float 8 (5)
s char[] bytes
p char[] bytes
P void * integer (6)