Convert bytes to bits in python

后端 未结 9 1676
轮回少年
轮回少年 2020-11-30 07:18

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 t

9条回答
  •  爱一瞬间的悲伤
    2020-11-30 08:11

    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.

提交回复
热议问题