Bitwise operation and usage

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

    i didnt see it mentioned, This example will show you the (-) decimal operation for 2 bit values: A-B (only if A contains B)

    this operation is needed when we hold an verb in our program that represent bits. sometimes we need to add bits (like above) and sometimes we need to remove bits (if the verb contains then)

    111 #decimal 7
    -
    100 #decimal 4
    --------------
    011 #decimal 3
    

    with python: 7 & ~4 = 3 (remove from 7 the bits that represent 4)

    001 #decimal 1
    -
    100 #decimal 4
    --------------
    001 #decimal 1
    

    with python: 1 & ~4 = 1 (remove from 1 the bits that represent 4 - in this case 1 is not 'contains' 4)..

提交回复
热议问题