Reputation: 110093
What is the correct way to pack a five-byte asci string into python so that it is 8-bytes and little endian? For example, something like:
from struct import pack
pack('<ccccc3x', 'David')
Or:
pack('<ccccc3x', b'D', b'a', b'v', b'i', b'd')
# this works but seems unreadable to me
What would be the correct (or simplest) way to do this? Ideally, something like:
>>> pack('<ccccc3x', *bytearray(b'David'))
But it seems I cannot pass a list or do variable-unpacking and I have to do a new positional argument for every character.
The best I can come up with is the following, but I'm hoping there's a better way to do it:
# why won't it allow me to use `c`(har) and only `b`(yte) ?
>>> pack('<5b3x', *bytearray(b'David'))
b'David\x00\x00\x00'
Update: seems like this might be the best way:
>>> pack('<5s3x', b'David')
b'David\x00\x00\x00'
Not sure though about all the different 'char'-ish types: s
, b
, and c
from the struct
page.
Upvotes: 2
Views: 509
Reputation: 168834
Endianness only is a thing for values more than a byte in size, so you don't need to worry about it here.
The most succinct way I can think of to pad a 5-byte bytestring to 8 bytes is
b'David'.ljust(8, b'\0')
Upvotes: 2