首页 > 解决方案 > 如何在 struct.pack 中打包字符串

问题描述

我正在尝试使用 struct.pack 打包字符串。如果我使用整数类型,我可以看到完整的值,但是当我想使用字符串时,我只能看到一个字符。

struct.pack("<1L",0xabcdabcd)
'\xab\xcd\ab\cd'
struct.pack("<1s","overflow")
'o' prints just s. I wanted it to print full string: overflow.

标签: python

解决方案


"<1s"在您传递给的格式字符串 ( ) 中struct.pack,1 表示该字段可以存储的最大字符数。(请参阅文档中“For the 's'...”开头的段落。)由于您传递 1,它只会存储第一个字符。您需要选择一个适合您要存储在结构中的任何字符串的长度,并指定它。例如,要存储字符串“溢出”(8 个字符),您可以使用:struct"<8s"

>>> struct.pack("<8s", "overflow")
'overflow'

推荐阅读