字符串/二进制数据到字节

发布于 2024-12-20 15:28:17 字数 437 浏览 5 评论 0原文

我是 Python 新手。我想将字符数组转换为字节缓冲区,即有没有办法将字符串或二进制数据的数据转换为字节缓冲区。

例如:如果 str = 'apple' 我需要 'apple' 的 buffer = bytes 值,我可以像 buffer[i] 和 < code>buffer[:j]

如果我使用 map(ord,'apple') 这会返回一个列表,但我需要一个连续缓冲区。我如何在 Python 中得到这个?

更新1:我还需要字节,因为今天它可能是字符串,但明天我可能会处理文件。

更新0:我想要以字节为单位。我可以按照 @ignacio 的建议使用字符串,但字符串不行。因为最终这将进入我的滚动哈希实现

Am new to Python. I want to convert a char array to byte buffer i.e. Is there any way to convert data which could be string or binary data to byte buffer.

Eg: if str = 'apple' I need buffer = bytes values of 'apple' which I can access like buffer[i] and buffer[:j]

If i use map(ord,'apple') this returns a list but I need a continuos buffer. How do I get this in Python ?

UPDATE 1: Also I need in bytes because today it might be strings but tomorrow I might be dealing with files.

UPDATE 0: I want it in bytes. I could have used strings as @ignacio suggests but strings just wont do. Because eventually this will go into my implementation of rolling hash

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

花心好男孩 2024-12-27 15:28:17

尝试bytearray。这会将源字符串转换为字节数组。有一个可选的编码参数,您需要指定该参数,以防 默认编码不是当前默认的字符串编码。

例子

>>> s = 'apple'
>>> arr=bytearray(s)
>>> [x for x in arr]
[97, 112, 112, 108, 101]
>>> type(arr)
<type 'bytearray'>
>>> 

Try bytearray. Which will convert the source string to an array of byte. There is an optional encoding parameter which you need to specify in case if the default encoding is not the current default string encoding.

Example

>>> s = 'apple'
>>> arr=bytearray(s)
>>> [x for x in arr]
[97, 112, 112, 108, 101]
>>> type(arr)
<type 'bytearray'>
>>> 
找个人就嫁了吧 2024-12-27 15:28:17

您可以在 python 中使用 struct 模块。

struct 模块包含用于在字符串之间进行转换的函数
字节和本机 Python 数据类型,例如数字和字符串。

You could use struct module in python.

The struct module includes functions for converting between strings of
bytes and native Python data types such as numbers and strings.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文