Bitwise operation and usage

前端 未结 16 1371
无人及你
无人及你 2020-11-22 00:57

Consider this code:

x = 1        # 0001
x << 2       # Shift left 2 bits: 0100
# Result: 4

x | 2        # Bitwise OR: 0011
# Result: 3

x & 1              


        
16条回答
  •  长情又很酷
    2020-11-22 01:14

    Whilst manipulating bits of an integer is useful, often for network protocols, which may be specified down to the bit, one can require manipulation of longer byte sequences (which aren't easily converted into one integer). In this case it is useful to employ the bitstring library which allows for bitwise operations on data - e.g. one can import the string 'ABCDEFGHIJKLMNOPQ' as a string or as hex and bit shift it (or perform other bitwise operations):

    >>> import bitstring
    >>> bitstring.BitArray(bytes='ABCDEFGHIJKLMNOPQ') << 4
    BitArray('0x142434445464748494a4b4c4d4e4f50510')
    >>> bitstring.BitArray(hex='0x4142434445464748494a4b4c4d4e4f5051') << 4
    BitArray('0x142434445464748494a4b4c4d4e4f50510')
    

提交回复
热议问题