encode Vs struct
-
I'm trying to get my head around the difference between
>>> struct.pack('4s', 'ping') b'ping'and
>>> 'ping'.encode() b'ping'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 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. -
@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 slotrtu=slot+rtu*16 packet=struct.pack('b', slotrtu) print(packet)to do it?
-
@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 & 0x0fis 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.
Hello! It looks like you're interested in this conversation, but you don't have an account yet.
Getting fed up of having to scroll through the same posts each visit? When you register for an account, you'll always come back to exactly where you were before, and choose to be notified of new replies (either via email, or push notification). You'll also be able to save bookmarks and upvote posts to show your appreciation to other community members.
With your input, this post could be even better 💗
Register Login