2

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.

1 Answer 1

2

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')
Sign up to request clarification or add additional context in comments.

2 Comments

Really neat solution
@AKX that's a great idea! I actually was doing the pack because I had a large bytearray and I was just appending/extending values to it, but yea for a asci-string I think this is much better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.