On Jul 12, 4:40 am, "albert_k_arhin" <[EMAIL PROTECTED]> wrote: > Hi All, > I am new to python and I am using a strip down version of > python that does not support struc,pack,etc. > > I have a binary protocol that is define as follows: > > PART OffSet Lenght > ============================ > ID 0 2 > VER 2 1 > CMD 3 2 > PGKID 5 2 > DATE 7 3 > TIME 10 3 > CRC 13 2 > DLEN 15 2 > > How do I encode these the offset is in Bytes. >
You haven't defined your data precisely enough to allow use of struct.pack even if it were available to you. Are all of the 1-byte fields unsigned integers (range 0 to 255 inclusive), or are some signed (range -128 to 127)? Are all of the 2-byte fields unsigned integers (range 0 to 65535 inclusive) or are some signed (-32768 to 32767)? What is the format of the 3-byte DATE and TIME fields? What type is your starting value -- datetime.datetime? Littlendian or bigendian? Here's an example of the sort of function you'll need to write: >>> def packu2le(anint): ... """Produce a 2-byte littlendian string from an unsigned integer""" ... assert 0 <= anint <= 65535 ... byte0 = anint & 0xff ... byte1 = anint >> 8 ... return chr(byte0) + chr(byte1) ... >>> packu2le(0) '\x00\x00' >>> packu2le(255) '\xff\x00' >>> packu2le(256) '\x00\x01' >>> packu2le(65535) '\xff\xff' >>> packu2le(-1) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in packu2le AssertionError >>> HTH, John -- http://mail.python.org/mailman/listinfo/python-list