Encode Bytes

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • albert_k_arhin

    #1

    Encode Bytes

    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.

    Thank you very much.

  • John Machin

    #2
    Re: Encode Bytes

    On Jul 12, 4:40 am, "albert_k_arhin " <albert_k_ar... @yahoo.comwrote :
    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.dateti me?
    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(25 5)
    '\xff\x00'
    >>packu2le(25 6)
    '\x00\x01'
    >>packu2le(6553 5)
    '\xff\xff'
    >>packu2le(-1)
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "<stdin>", line 2, in packu2le
    AssertionError
    >>>
    HTH,
    John



    Comment

    Working...