(Number and Number) in VBscript

拥有回忆 提交于 2020-06-14 07:51:48

问题


I have some VB script in classic ASP that looks like this:

if (x and y) > 0 then
    'do something
end if

It seems to work like this: (46 and 1) = 0 and (47 and 1) = 1

I don't understand how that works. Can someone explain that?


回答1:


It's a Bitwise AND.

    47 is 101111
AND  1 is 000001
        = 000001

while

    46 is 101110
AND  1 is 000001
        = 000000



回答2:


It's doing a bitwise comparison -

Bitwise operations evaluate two integral values in binary (base 2) form. They compare the bits at corresponding positions and then assign values based on the comparison.

and a further example -

x = 3 And 5

The preceding example sets the value of x to 1. This happens for the following reasons:

The values are treated as binary:

3 in binary form = 011

5 in binary form = 101

The And operator compares the binary representations, one binary position (bit) at a time. If both bits at a given position are 1, then a 1 is placed in that position in the result. If either bit is 0, then a 0 is placed in that position in the result. In the preceding example this works out as follows:

011 (3 in binary form)

101 (5 in binary form)

001 (The result, in binary form)

The result is treated as decimal. The value 001 is the binary representation of 1, so x = 1.

From - http://msdn.microsoft.com/en-us/library/wz3k228a(v=vs.80).aspx




回答3:


Try

x = 47
y = -1

if (x AND y) > 0 then
    'erroneously passes condition instead of failing
end if


Code should be

if (x > 0) AND (y > 0) then
    'do something
end if

and then it'll work as expected.



来源:https://stackoverflow.com/questions/7766375/number-and-number-in-vbscript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!