Previous topicNext topic
Help > 开发指南 > 编程基础 > VB编程基础 > 运算符 >
位移运算符
我们已经讨论了按位运算符。 位移运算符对二进制值执行移位操作。 在进入位移运算符之前,让我们来了解位操作。

按位运算符处理位并执行逐位操作。 &,|和^的真值表如下:

p q p&Q p | q p ^ Q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1

假设A = 60; 和B = 13; 现在的二进制格式,他们将如下:


A = 0011 1100

B = 0000 1101

-----------------

A&B = 0000 1100

A | B = 0011 1101

A ^ B = 0011 0001

?A = 1100 0011


我们已经看到VB.Net支持的Bitwise运算符是And,Or,Xor和Not。 位移位算子分别是用于左移和右移的>>和<<。

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

运算符 描述 示例
And 如果两个操作数都存在,则按位AND运算符将一个位复制到结果。 (A AND B) will give 12, which is 0000 1100
Or 二进制OR运算符复制一个位,如果它存在于任一操作数。 (A Or B) will give 61, which is 0011 1101
Xor 二进制XOR运算符复制该位,如果它在一个操作数中设置,但不是两个操作数。 (A Xor B) will give 49, which is 0011 0001
Not 二进制补码运算符是一元的,具有“翻转”位的效果。 (Not A ) will give -61, which is 1100 0011 in 2's complement form due to a signed binary number.
<< 二进制左移位运算符。 左操作数值向左移动由右操作数指定的位数。 A << 2 will give 240, which is 1111 0000
>> 二进制右移运算符。 左操作数值向右移动由右操作数指定的位数。 A >> 2 will give 15, which is 0000 1111

 

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

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
Proj.MsgDebug.Add("Line 1 - Value of c is {0}", c)
c = a Or b       ' 61 = 0011 1101
Proj.MsgDebug.Add("Line 2 - Value of c is {0}", c)
c = a Xor b       ' 49 = 0011 0001
Proj.MsgDebug.Add("Line 3 - Value of c is {0}", c)
c = Not a          ' -61 = 1100 0011
Proj.MsgDebug.Add("Line 4 - Value of c is {0}", c)
c = a << 2     ' 240 = 1111 0000
Proj.MsgDebug.Add("Line 5 - Value of c is {0}", c)
c = a >> 2    ' 15 = 0000 1111
Proj.MsgDebug.Add("Line 6 - Value of c is {0}", c)

'返回结果: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