简体   繁体   English

在python中打包字符串的正确方法

[英]Proper way to pack a string in python

What is the correct way to pack a five-byte asci string into python so that it is 8-bytes and little endian?将一个五字节的 asci 字符串打包到 python 中以便它是 8 字节和小端的正确方法是什么? 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.尽管不确定struct页面中所有不同的“char”类型: sbc

Endianness only is a thing for values more than a byte in size, so you don't need to worry about it here. Endianness 仅适用于大小超过一个字节的值,因此您无需在此处担心。

The most succinct way I can think of to pad a 5-byte bytestring to 8 bytes is我能想到的将 5 字节字节串填充为 8 字节的最简洁方法是

b'David'.ljust(8, b'\0')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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