Bitwise operation and usage

前端 未结 16 1393
无人及你
无人及你 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:22

    To flip bits (i.e. 1's complement/invert) you can do the following:

    Since value ExORed with all 1s results into inversion, for a given bit width you can use ExOR to invert them.

    In Binary
    a=1010 --> this is 0xA or decimal 10
    then 
    c = 1111 ^ a = 0101 --> this is 0xF or decimal 15
    -----------------
    In Python
    a=10
    b=15
    c = a ^ b --> 0101
    print(bin(c)) # gives '0b101'
    

提交回复
热议问题