VB.Net - 移位运算符

由 youj 创建, 最后一次修改 2016-12-15

假设变量A保持60,变量B保持13,则:

运算符描述示例
AndBitwise AND Operator copies a bit to the result if it exists in both operands.
如果两个操作数都存在,则位与运算符将一个位复制到结果。
(A AND B) will give 12, which is 0000 1100
OrBinary OR Operator copies a bit if it exists in either operand.
二进制OR运算符复制一个位,如果它存在于任一操作数。
(A Or B) will give 61, which is 0011 1101
XorBinary XOR Operator copies the bit if it is set in one operand but not both.
二进制XOR运算符复制该位,如果它在一个操作数中设置,但不是两个操作数。
(A Xor B) will give 49, which is 0011 0001
NotBinary Ones Complement Operator is unary and has the effect of 'flipping' bits.
二进制补码运算符是一元的,具有“翻转”位的效果。
(Not A ) will give -61, which is 1100 0011 in 2's complement form due to a signed binary number.
<<Binary Left Shift Operator. The left operand's value is moved left by the number of bits specified by the right operand.
二进制左移位运算符。 左操作数的值向左移动由右操作数指定的位数。
A << 2 will give 240, which is 1111 0000
>>Binary Right Shift Operator. The left operand's value is moved right by the number of bits specified by the right operand.
二进制右移运算符。 左操作数的值向右移动由右操作数指定的位数。
A >> 2 will give 15, which is 0000 1111

尝试以下示例来了解VB.Net中提供的所有位运算符:

Module BitwiseOp
   Sub Main()
      Dim a As Integer = 60       ' 60 = 0011 1100   
      Dim b As Integer = 13       ' 13 = 0000 1101
      Dim c As Integer = 0
      c = a And b       ' 12 = 0000 1100 
      Console.WriteLine("Line 1 - Value of c is {0}", c)
      c = a Or b       ' 61 = 0011 1101 
      Console.WriteLine("Line 2 - Value of c is {0}", c)
      c = a Xor b       ' 49 = 0011 0001 
      Console.WriteLine("Line 3 - Value of c is {0}", c)
      c = Not a          ' -61 = 1100 0011 
      Console.WriteLine("Line 4 - Value of c is {0}", c)
      c = a << 2     ' 240 = 1111 0000 
      Console.WriteLine("Line 5 - Value of c is {0}", c)
      c = a >> 2    ' 15 = 0000 1111 
      Console.WriteLine("Line 6 - Value of c is {0}", c)
      Console.ReadLine()
   End Sub
End Module

当上述代码被编译和执行时,它产生以下结果:

Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15

以上内容是否对您有帮助:

二维码
建议反馈
二维码