Python 位运算与使用

Python 位运算与使用,python,binary,operators,bit-manipulation,Python,Binary,Operators,Bit Manipulation,考虑以下代码: x = 1 # 0001 x << 2 # Shift left 2 bits: 0100 # Result: 4 x | 2 # Bitwise OR: 0011 # Result: 3 x & 1 # Bitwise AND: 0001 # Result: 1 x=1#0001 x一种典型用法: |用于将特定位设置为1 &用于测试或清除特定位 设置位(其中n为位号,0为最低有效位): 无符号字符

考虑以下代码:

x = 1        # 0001
x << 2       # Shift left 2 bits: 0100
# Result: 4

x | 2        # Bitwise OR: 0011
# Result: 3

x & 1        # Bitwise AND: 0001
# Result: 1
x=1#0001
x一种典型用法:

|
用于将特定位设置为1

&
用于测试或清除特定位

  • 设置位(其中n为位号,0为最低有效位):

    无符号字符a |=(1一种典型用法:

    |
    用于将特定位设置为1

    &
    用于测试或清除特定位

    • 设置位(其中n为位号,0为最低有效位):


      unsigned char a |=(1按位运算符是处理多位值的运算符,但在概念上是一次一位

      • 仅当其两个输入均为1时才为1,否则为0
      • 如果一个或两个输入都为1,则为1,否则为0
      • XOR
        仅当其一个输入为1时才为1,否则为0
      • NOT
        仅当其输入为0时才为1,否则为0
      这些通常可以最好地显示为真值表。输入可能性在顶部和左侧,结果位是显示在输入交点处的四个值之一(非的情况下为两个,因为它只有一个输入)

      AND | 0 1     OR | 0 1     XOR | 0 1    NOT | 0 1
      ----+-----    ---+----     ----+----    ----+----
       0  | 0 0      0 | 0 1       0 | 0 1        | 1 0
       1  | 0 1      1 | 1 1       1 | 1 0
      
      一个例子是,如果您只需要整数的低位4位,则可以使用15(二进制1111)将其与之相加,因此:

      在这种情况下,15中的零位有效地充当过滤器,迫使结果中的位也为零


      此外,
      >
      按位运算符是处理多位值的运算符,但概念上一次处理一位

      • 仅当其两个输入均为1时才为1,否则为0
      • 如果一个或两个输入都为1,则为1,否则为0
      • XOR
        仅当其一个输入为1时才为1,否则为0
      • NOT
        仅当其输入为0时才为1,否则为0
      这些通常可以最好地显示为真值表。输入可能性在顶部和左侧,结果位是显示在输入交点处的四个值之一(非的情况下为两个,因为它只有一个输入)

      AND | 0 1     OR | 0 1     XOR | 0 1    NOT | 0 1
      ----+-----    ---+----     ----+----    ----+----
       0  | 0 0      0 | 0 1       0 | 0 1        | 1 0
       1  | 0 1      1 | 1 1       1 | 1 0
      
      一个例子是,如果您只需要整数的低位4位,则可以使用15(二进制1111)将其与之相加,因此:

      在这种情况下,15中的零位有效地充当过滤器,迫使结果中的位也为零


      此外,
      >
      我希望这能澄清这两个问题:

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


      我希望这能澄清这两个问题:

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


      将0视为false,将1视为true。然后按位and(&)和or(|)就像常规and和or一样工作,只是它们同时执行值中的所有位。通常,如果您有30个可设置的选项(例如窗口上的绘图样式),您会看到它们用于标志您不希望必须传入30个单独的布尔值来设置或取消设置每个值,因此您可以使用|将选项组合成单个值,然后使用&检查每个选项是否已设置。OpenGL大量使用这种类型的标志传递。由于每一位都是单独的标志,因此可以通过2的幂获得标志值(亦称仅设置了一位的数字)1(2^0)2(2^1)4(2^2)8(2^3)如果标志打开,则二的幂告诉您设置了哪个位


      另请注意2=10,因此如果没有任何位重叠(在本例中为true),那么x | 2是110(6)而不是111(7)|的行为类似于加法。

      将0视为false,1视为true。然后按位and(&)和or(|)与常规and或or一样工作,只是它们一次完成值中的所有位。通常,如果您有30个可设置的选项(例如,窗口上的绘图样式),您将看到它们用于标记您不希望必须传入30个单独的布尔值来设置或取消设置每个值,因此您可以使用|将选项组合成单个值,然后使用&检查每个选项是否已设置。OpenGL大量使用这种类型的标志传递。由于每一位都是单独的标志,因此可以通过2的幂获得标志值(亦称仅设置了一位的数字)1(2^0)2(2^1)4(2^2)8(2^3)如果标志打开,则二的幂告诉您设置了哪个位

      另请注意2=10,因此如果没有任何位重叠(在本例中为真),那么x | 2是110(6)而不是111(7)|作为加法

      位运算符的实际用途是什么?我希望有一些例子

      位运算最常见的用途之一是解析十六进制颜色

      例如,这里有一个函数,它接受类似
      #FF09BE
      的字符串,并返回其红色、绿色和蓝色值的元组

      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)
      
      我知道有更有效的方法来实现这一点,但我相信这是一个非常简洁的例子,说明了移位和按位布尔运算

      位运算符的实际用途是什么?我希望有一些例子

      位运算最常见的用途之一是解析十六进制颜色

      例如,这里有一个函数,它接受类似
      #FF09BE
      的字符串,并返回其红色、绿色和蓝色值的元组

      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)
      

      我知道有更有效的方法来实现这一点,但我相信这是一个非常简洁的示例,说明了移位和按位布尔运算。

      另一个常见的用例是操作/测试文件权限。请参阅Python stat模块:

      例如,要将文件的权限与所需的权限集进行比较,可以执行以下操作:

      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)
      

      我将结果转换为布尔值,因为我只关心真相或谬误,但打印每个值的bin()值是一个值得的练习。

      另一个常见用例是操作/测试文件权限。请参阅Python stat模块:

      例如,要将文件的权限与所需的权限集进行比较,可以执行以下操作:

      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)
      
      我把结果投成布尔人,因为我只关心真相或谬误,但事实并非如此
      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)
      
      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)
      
      10 | 12
      
      1010 #decimal 10
      1100 #decimal 12
      
      1110 #result = 14
      
      10 & 12
      
      1010 #decimal 10
      1100 #decimal 12
      
      1000 #result = 8
      
      x = raw_input('Enter a number:')
      print 'x is %s.' % ('even', 'odd')[x&1]
      
      read = ((read ^ 0x80) >> 4) & 0x0f; 
      
      import numpy as np
      a=np.array([1.2, 2.3, 3.4])
      np.where((a>2) and (a<3))      
      #Result: Value Error
      np.where((a>2) & (a<3))
      #Result: (array([1]),)
      
      111 #decimal 7
      -
      100 #decimal 4
      --------------
      011 #decimal 3
      
      001 #decimal 1
      -
      100 #decimal 4
      --------------
      001 #decimal 1
      
      >>> import bitstring
      >>> bitstring.BitArray(bytes='ABCDEFGHIJKLMNOPQ') << 4
      BitArray('0x142434445464748494a4b4c4d4e4f50510')
      >>> bitstring.BitArray(hex='0x4142434445464748494a4b4c4d4e4f5051') << 4
      BitArray('0x142434445464748494a4b4c4d4e4f50510')
      
      first = {1, 2, 3, 4, 5, 6}
      second = {4, 5, 6, 7, 8, 9}
      
      print(first | second)
      
      print(first & second)
      
      print(first - second)
      
      print(second - first)
      
      print(first ^ second)
      
      {1, 2, 3, 4, 5, 6, 7, 8, 9}
      
      {4, 5, 6}
      
      {1, 2, 3}
      
      {8, 9, 7}
      
      {1, 2, 3, 7, 8, 9}
      
      In Binary
      a=1010 --> this is 0xA or decimal 10
      then 
      c = 1111 ^ a = 0101 --> this is 0xF or decimal 15
      -----------------
      In Python
      a=10
      b=15
      c = a ^ b --> 0101
      print(bin(c)) # gives '0b101'