简体   繁体   中英

Why can't Python struct module pack (or unpack) multi bytes with little endian

I'm dealing with some multi bytes issues. For example, I have a variable a = b'\\x00\\x01\\x02\\x03' , it is a bytes object rather than int . I'd like to struct.pack it to form a package with little endian , but <4s didn't work. In fact, <4s and >4s get the same results. What to do if I'd like the result to be b'\\x03\\x02\\x01\\x00 .
I know I could use struct.pack('<L', struct.unpack('>L', a)) , but is it the only and correct way to deal with multi bytes objects?

Example:

import struct
import secrets

mhdr = b'\x20'
joineui = b'\x00\x01\x02\x03\x04\x05\x06\x07'
deveui = b'\x08\x09\x10\x11\x12\x13\x14\x15'
devnonce = secrets.token_bytes(2)

joinreq = struct.pack(
    '<s8s8s2s',
    mhdr,
    joineui,
    deveui,
    devnonce,
)

# The expected joinreq should be b'\x20\x07\x06\x05\x04\x03\x02\x01\x00\x15\x14\x13\x12\x11\x10\x09\x08...'

It seems to me you do not want to have 4 single chars, but instead 1 integer. So instead of '4s' you should try using 'i' or 'I' (whether it is signed or unsigned).

Your example should look like

import struct
import secrets

mhdr = b'\x20'
joineui = b'\x00\x01\x02\x03\x04\x05\x06\x07'
deveui = b'\x08\x09\x10\x11\x12\x13\x14\x15'
devnonce = secrets.token_bytes(2)

joinreq = struct.pack(
    '<BQQH', #use small letters if the values are signed instead of unsigned
    mhdr,
    joineui,
    deveui,
    devnonce,
)

"Q" stands for long long unsigned (8byte). If you want to use float instead you can use d for double float precision (8byte).

You can see the meaning of all letters in the documentation of struct .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM