Bitwise operation and usage

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

    what are bitwise operators actually used for? I'd appreciate some examples.

    One of the most common uses of bitwise operations is for parsing hexadecimal colours.

    For example, here's a Python function that accepts a String like #FF09BE and returns a tuple of its Red, Green and Blue values.

    def hexToRgb(value):
        # Convert string to hexadecimal number (base 16)
        num = (int(value.lstrip("#"), 16))
    
        # Shift 16 bits to the right, and then binary AND to obtain 8 bits representing red
        r = ((num >> 16) & 0xFF)
    
        # Shift 8 bits to the right, and then binary AND to obtain 8 bits representing green
        g = ((num >> 8) & 0xFF)
    
        # Simply binary AND to obtain 8 bits representing blue
        b = (num & 0xFF)
        return (r, g, b)
    

    I know that there are more efficient ways to acheive this, but I believe that this is a really concise example illustrating both shifts and bitwise boolean operations.

提交回复
热议问题