Convert bytes to bits in python

后端 未结 9 1672
轮回少年
轮回少年 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:47

    What about something like this?

    >>> bin(int('ff', base=16))
    '0b11111111'
    

    This will convert the hexadecimal string you have to an integer and that integer to a string in which each byte is set to 0/1 depending on the bit-value of the integer.

    As pointed out by a comment, if you need to get rid of the 0b prefix, you can do it this way:

    >>> bin(int('ff', base=16)).lstrip('0b')
    '11111111'
    

    or this way:

    >>> bin(int('ff', base=16))[2:]
    '11111111'
    

提交回复
热议问题