Bitwise operation and usage

前端 未结 16 1365
无人及你
无人及你 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: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, ^.

提交回复
热议问题