Convert bytes to bits in python

后端 未结 9 1682
轮回少年
轮回少年 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 07:52

    The other answers here provide the bits in big-endian order ('\x01' becomes '00000001')

    In case you're interested in little-endian order of bits, which is useful in many cases, like common representations of bignums etc - here's a snippet for that:

    def bits_little_endian_from_bytes(s):
        return ''.join(bin(ord(x))[2:].rjust(8,'0')[::-1] for x in s)
    

    And for the other direction:

    def bytes_from_bits_little_endian(s):
        return ''.join(chr(int(s[i:i+8][::-1], 2)) for i in range(0, len(s), 8))
    

提交回复
热议问题