And、Or和Xor:让我们来优化表达式

发布时间:2008-6-30 22:39:33文章来源:佚名浏览次数:
选择您适合观看的字体大小:  
要检测一个整数值的最高有效位是否有数值,通常要使用如下的代码(有二种情况:第一组if判断表明对integer类型,第二组对long类型):  

if intvalue and &h8000 then  

’ most significant bit is set  

end if  

if lngvalue and &h80000000 then  

’ most significant bit is set  

end if  

但由于所有的vb变量都是有符号的,因此,最高有效位也是符号位,不管处理什么类型的数值,通过下面的代码就可以实现检测目的:  

if anyvalue < 0 then  

’ most significant bit is set  

end if  

另外,要检测2个或者更多个数值的符号,只需要通过一个bit位与符号位的简单表达式就可以完成。下面是应用这个技术的几段具体代码:  

1、判断x和y是否为同符号数值:  

if (x < 0 and y < 0) or (x >= 0 and y >=0) then ...  

’ the optimized approach  

if (x xor y) >= 0 then  

2、判断x、y和z是否都为正数  

if x >= 0 and y >= 0 and z >= 0 then ...  

’ the optimized approach  

if (x or y or z) >= 0 then ...  

3、判断x、y和z是否都为负数  

if x < 0 and y < 0 and z < 0 then ...  

’ the optimized approach  

if (x and y and z) < 0 then ...  

4、判断x、y和z是否都为0  

if x = 0 and y = 0 and z = 0 then ...  

’ the optimized approach  

if (x or y or z) = 0 then ...  

5、判断x、y和z是否都不为0  

if x = 0 and y = 0 and z = 0 then ...  

’ the optimized approach  

if (x or y or z) = 0 then ...  

要使用这些来简单化一个复杂的表达式,必须要完全理解boolean型的操作原理。比如,你可能会认为下面的2行代码在功能上是一致的:  

if x <> 0 and y <> 0 then  

if (x and y) then ...  

然而我们可以轻易地证明他们是不同的,比如x=3(二进制=0011),y=4(二进制=0100)。不过没有关系,遇到这种情况时,我们可以对上面的代码进行局部优化,就能实现目的。代码如下:  

if (x <> 0) and y then ...  
  打印新闻关闭窗口