我有一个整数ascii值列表,我需要将其转换为字符串(二进制)以用作加密操作的键.(我在python中重新实现java加密代码)
这有效(假设一个8字节的密钥):
key = struct.pack('BBBBBBBB', 17, 24, 121, 1, 12, 222, 34, 76)
Run Code Online (Sandbox Code Playgroud)
但是,我宁愿没有密钥长度和硬盘编码的unpack()参数列表.
在给定初始的整数列表的情况下,如何正确实现?
谢谢!
Sco*_*ths 56
对于Python 2.6及更高版本,如果您处理字节,则a bytearray
是最明显的选择:
>>> str(bytearray([17, 24, 121, 1, 12, 222, 34, 76]))
'\x11\x18y\x01\x0c\xde"L'
Run Code Online (Sandbox Code Playgroud)
对我来说,这比Alex Martelli的回答更直接 - 仍然没有字符串操作或len
调用,但现在你甚至不需要导入任何东西!
Ale*_*lli 46
对于这类任务,我更喜欢array
模块到struct
模块(涉及齐次值序列的模块):
>>> import array
>>> array.array('B', [17, 24, 121, 1, 12, 222, 34, 76]).tostring()
'\x11\x18y\x01\x0c\xde"L'
Run Code Online (Sandbox Code Playgroud)
没有len
电话,不需要字符串操作等 - 快速,简单,直接,为什么更喜欢任何其他方法?!
Pi *_*ort 38
这是一个老问题,但在Python 3中,您可以直接使用bytes
:
>>> bytes([17, 24, 121, 1, 12, 222, 34, 76])
b'\x11\x18y\x01\x0c\xde"L'
Run Code Online (Sandbox Code Playgroud)
小智 11
struct.pack('B' * len(integers), *integers)
Run Code Online (Sandbox Code Playgroud)
*sequence
意思是"解包顺序" - 或者更确切地说,"当打电话时f(..., *args ,...)
,让args = sequence
".