将字节转换为python中的位 [英] Convert bytes to bits in python

查看:1579
本文介绍了将字节转换为python中的位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python3.2。我需要将十六进制流作为输入并在比特级解析它。所以我使用了

bytes.fromhex(input_str)



将字符串转换为实际字节。现在我该如何将这些字节转换为位?解析方案

另一种方法是使用 bitstring 模块:

 >>> from bitstring import BitArray 
>>> input_str ='0xff'
>>> c = BitArray(hex = input_str)
>>> c.bin
'0b11111111'

如果你需要去掉领先的 0b

 >>> c.bin [2:] 
'11111111'

bitstring 模块并不是必需的,因为 jcollado 的答案显示,但它有许多用于将输入转换为位并操作它们的高性能方法。例如:你可能会发现这个方便(或不),例如:

 >>> c.uint 
255
>>> c.invert()
>>> c.bin [2:]
'00000000'

等。


I am working with Python3.2. I need to take a hex stream as an input and parse it at bit-level. So I used

bytes.fromhex(input_str)

to convert the string to actual bytes. Now how do I convert these bytes to bits?

解决方案

Another way to do this is by using the bitstring module:

>>> from bitstring import BitArray
>>> input_str = '0xff'
>>> c = BitArray(hex=input_str)
>>> c.bin
'0b11111111'

And if you need to strip the leading 0b:

>>> c.bin[2:]
'11111111'

The bitstring module isn't a requirement, as jcollado's answer shows, but it has lots of performant methods for turning input into bits and manipulating them. You might find this handy (or not), for example:

>>> c.uint
255
>>> c.invert()
>>> c.bin[2:]
'00000000'

etc.

这篇关于将字节转换为python中的位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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