Convert bytes to bits in python

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

    Operations are much faster when you work at the integer level. In particular, converting to a string as suggested here is really slow.

    If you want bit 7 and 8 only, use e.g.

    val = (byte >> 6) & 3
    

    (this is: shift the byte 6 bits to the right - dropping them. Then keep only the last two bits 3 is the number with the first two bits set...)

    These can easily be translated into simple CPU operations that are super fast.

提交回复
热议问题