encode Vs struct

  • I'm trying to get my head around the difference between

    >>> struct.pack('4s', 'ping')


    >>> 'ping'.encode()

    is it just an a case of doing the same thing 2 different ways or is there some subtle difference I'm missing? I'm trying to figure out if there is a way to reduce the payload size of an epoch (10digits) sent over rawlora as per https://forum.pycom.io/topic/5555/lopy4-to-lopy4-over-lora-raw-pack-string/5.

  • @kjm That's a good way doing it. As a matter of preference & PEP8 coding style I would write it as:

    import struct
    slot = 15
    rtu = 14
    slotrtu = (slot & 0x0f)  | (rtu << 4) 
    packet = struct.pack('B', slotrtu)

    Using binary operators instead of arithmetic ones results in the same value but expresses more clearly the intention. And using slot & 0x0f is more a 'belt and straps' attitude.
    The only important change is using B instead of b, indicating that the number is unsigned, which however mostly matters on unpack.

  • @robert-hh So if I want to pack two 0-15 range variables into a byte, is there a better way than

    import struct
    slot=15; rtu=14
    packet=struct.pack('b', slotrtu)

    to do it?

  • @kjm I epoch is a number < 2^32, you can pack that as binary value using struct.pack("L", epoch). That will result in a 4 bytes object of 4 bytes length.
    Larger numbers may have to be split.

Log in to reply

Pycom on Twitter