Bitwise operation and usage

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

    This example will show you the operations for all four 2 bit values:

    10 | 12
    
    1010 #decimal 10
    1100 #decimal 12
    
    1110 #result = 14
    

    10 & 12
    
    1010 #decimal 10
    1100 #decimal 12
    
    1000 #result = 8
    

    Here is one example of usage:

    x = raw_input('Enter a number:')
    print 'x is %s.' % ('even', 'odd')[x&1]
    

提交回复
热议问题