Bitwise operation and usage

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

    Another common use-case is manipulating/testing file permissions. See the Python stat module: http://docs.python.org/library/stat.html.

    For example, to compare a file's permissions to a desired permission set, you could do something like:

    import os
    import stat
    
    #Get the actual mode of a file
    mode = os.stat('file.txt').st_mode
    
    #File should be a regular file, readable and writable by its owner
    #Each permission value has a single 'on' bit.  Use bitwise or to combine 
    #them.
    desired_mode = stat.S_IFREG|stat.S_IRUSR|stat.S_IWUSR
    
    #check for exact match:
    mode == desired_mode
    #check for at least one bit matching:
    bool(mode & desired_mode)
    #check for at least one bit 'on' in one, and not in the other:
    bool(mode ^ desired_mode)
    #check that all bits from desired_mode are set in mode, but I don't care about 
    # other bits.
    not bool((mode^desired_mode)&desired_mode)
    

    I cast the results as booleans, because I only care about the truth or falsehood, but it would be a worthwhile exercise to print out the bin() values for each one.

提交回复
热议问题