简体   繁体   English

在 Python 中将 ASCII 码列表转换为字符串(字节数组)

[英]Convert list of ASCII codes to string (byte array) in Python

I have a list of integer ASCII values that I need to transform into a string (binary) to use as the key for a crypto operation.我有一个整数 ASCII 值列表,我需要将其转换为字符串(二进制)以用作加密操作的密钥。 (I am re-implementing java crypto code in python) (我正在用 python 重新实现 java 加密代码)

This works (assuming an 8-byte key):这有效(假设一个 8 字节的密钥):

key = struct.pack('BBBBBBBB', 17, 24, 121, 1, 12, 222, 34, 76)

However, I would prefer to not have the key length and unpack() parameter list hardcoded.但是,我宁愿不对密钥长度和 unpack() 参数列表进行硬编码。

How might I implement this correctly, given an initial list of integers?给定初始整数列表,我该如何正确实现?

Thanks!谢谢!

For Python 2.6 and later if you are dealing with bytes then a bytearray is the most obvious choice:对于 Python 2.6 及更高版本,如果您正在处理字节,那么字节bytearray是最明显的选择:

>>> str(bytearray([17, 24, 121, 1, 12, 222, 34, 76]))
'\x11\x18y\x01\x0c\xde"L'

To me this is even more direct than Alex Martelli's answer - still no string manipulation or len call but now you don't even need to import anything!对我来说,这比 Alex Martelli 的回答更直接——仍然没有字符串操作或len调用,但现在你甚至不需要导入任何东西!

I much prefer the array module to the struct module for this kind of tasks (ones involving sequences of homogeneous values):对于这种任务(涉及同质值序列的任务),我更喜欢array模块而不是struct模块:

>>> import array
>>> array.array('B', [17, 24, 121, 1, 12, 222, 34, 76]).tostring()
'\x11\x18y\x01\x0c\xde"L'

no len call, no string manipulation needed, etc -- fast, simple, direct, why prefer any other approach?!没有len调用,不需要字符串操作等等——快速、简单、直接,为什么更喜欢其他方法?!

This is reviving an old question, but in Python 3, you can just use bytes directly:这是一个老问题,但在 Python 3 中,您可以直接使用bytes

>>> bytes([17, 24, 121, 1, 12, 222, 34, 76])
b'\x11\x18y\x01\x0c\xde"L'
struct.pack('B' * len(integers), *integers)

*sequence means "unpack sequence" - or rather, "when calling f(..., *args,...) , let args = sequence ". *sequence的意思是“解包序列”——或者更确切地说,“当调用f(..., *args,...)时,让args = sequence ”。

key = "".join( chr( val ) for val in myList )

Shorter version of previous using map() function (works for python 2.7):以前使用map()函数的较短版本(适用于 python 2.7):

"".join(map(chr, myList))

另一种方法(Python 2.7+):

"".join(str(x) for x in int_array)

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

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