在Python 3中将二进制字符串转换为字节数组 [英] Convert binary string to bytearray in Python 3

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

问题描述

尽管有许多相关问题,但找不到与我的问题相符的问题.我想将二进制字符串(例如,"0110100001101001")更改为字节数组(相同的示例,b"hi").

Despite the many related questions, I can't find any that match my problem. I'd like to change a binary string (for example, "0110100001101001") into a byte array (same example, b"hi").

我尝试过:

bytes([int(i) for i in "0110100001101001"])

但是我得到了

b'\x00\x01\x01\x00\x01' #... and so on

在Python 3中执行此操作的正确方法是什么?

What's the correct way to do this in Python 3?

推荐答案

下面是Patrick提到的第一种方法:将位串转换为int并一次取8位.这样做的自然方法是按相反的顺序生成字节.为了使字节恢复正确的顺序,我对字节数组使用了扩展的切片符号,步长为-1:b[::-1].

Here's an example of doing it the first way that Patrick mentioned: convert the bitstring to an int and take 8 bits at a time. The natural way to do that generates the bytes in reverse order. To get the bytes back into the proper order I use extended slice notation on the bytearray with a step of -1: b[::-1].

def bitstring_to_bytes(s):
    v = int(s, 2)
    b = bytearray()
    while v:
        b.append(v & 0xff)
        v >>= 8
    return bytes(b[::-1])

s = "0110100001101001"
print(bitstring_to_bytes(s))

很显然,帕特里克的第二种方法更紧凑. :)

Clearly, Patrick's second way is more compact. :)

但是,在Python 3中有一种更好的方法:使用 int.to_bytes 方法:

However, there's a better way to do this in Python 3: use the int.to_bytes method:

def bitstring_to_bytes(s):
    return int(s, 2).to_bytes(len(s) // 8, byteorder='big')

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

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