Bitwise operation and usage

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

    One typical usage:

    | is used to set a certain bit to 1

    & is used to test or clear a certain bit

    • Set a bit (where n is the bit number, and 0 is the least significant bit):

      unsigned char a |= (1 << n);

    • Clear a bit:

      unsigned char b &= ~(1 << n);

    • Toggle a bit:

      unsigned char c ^= (1 << n);

    • Test a bit:

      unsigned char e = d & (1 << n);

    Take the case of your list for example:

    x | 2 is used to set bit 1 of x to 1

    x & 1 is used to test if bit 0 of x is 1 or 0

提交回复
热议问题