我想将Python3中的字节数组转换为二进制数据,以便对其进行操作。
例如,让我们假设我们有以下内容:
a = bytearray(b'\x10\x10\x10')
然后:
a)我想以二进制形式显示a
,例如b = 0b100000001000000010000
。
b)我希望能够从先前数据中选择一些位(其中最低有效位以某种方式对应于b[0]
),例如b[4:8] = 0b0001
。
我们如何在Python中做到这一点呢?
非常感谢。
发布于 2021-03-02 01:12:09
@Axe319
你的帖子只部分回答了我的问题。
感谢你,我得到了:
import sys
a = bytearray(b'\x10\x10\x10')
b = bin(int.from_bytes(state, byteorder=sys.byteorder))
print(b)
0b100000001000000010000
然后,为了选择四位,我在Python: How do I extract specific bits from a byte?中找到
def access_4bits(data, num):
# access 4 bits from num-th position in data
return bin(int(data, 2) >> num & 0b1111)
c = access_4bits(b, 4)
print(c)
0b1
https://stackoverflow.com/questions/66426231
复制相似问题