Bitwise operation and usage

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

    I hope this clarifies those two:

    x | 2
    
    0001 //x
    0010 //2
    
    0011 //result = 3
    

    x & 1
    
    0001 //x
    0001 //1
    
    0001 //result = 1
    
    0 讨论(0)
  • 2020-11-22 01:26

    Bit representations of integers are often used in scientific computing to represent arrays of true-false information because a bitwise operation is much faster than iterating through an array of booleans. (Higher level languages may use the idea of a bit array.)

    A nice and fairly simple example of this is the general solution to the game of Nim. Take a look at the Python code on the Wikipedia page. It makes heavy use of bitwise exclusive or, ^.

    0 讨论(0)
  • 2020-11-22 01:28

    the following bitwise operators: &, |, ^, and ~ return values (based on their input) in the same way logic gates affect signals. You could use them to emulate circuits.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题