在 Python 中将 ASCII 代码列表转换为字符串(字节数组) [英] Convert list of ASCII codes to string (byte array) in Python

查看:88
本文介绍了在 Python 中将 ASCII 代码列表转换为字符串(字节数组)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个整数 ASCII 值列表,我需要将其转换为字符串(二进制)以用作加密操作的密钥.(我正在python中重新实现java加密代码)

这有效(假设密钥为 8 字节):

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

但是,我不希望对密钥长度和 unpack() 参数列表进行硬编码.

给定初始整数列表,我该如何正确实现?

谢谢!

解决方案

我更喜欢 array 模块到 struct 模块用于此类任务(涉及同类值序列的任务):

<预><代码>>>>导入数组>>>array.array('B', [17, 24, 121, 1, 12, 222, 34, 76]).tostring()'\x11\x18y\x01\x0c\xde"L'

没有 len 调用,不需要字符串操作等——快速、简单、直接,为什么更喜欢其他方法?!

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. (I am re-implementing java crypto code in python)

This works (assuming an 8-byte key):

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.

How might I implement this correctly, given an initial list of integers?

Thanks!

解决方案

I much prefer the array module to the struct module for this kind of tasks (ones involving sequences of homogeneous values):

>>> 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?!

这篇关于在 Python 中将 ASCII 代码列表转换为字符串(字节数组)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆