Positonic
Positonic

Reputation: 9411

(Number and Number) in VBscript

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?

Upvotes: 4

Views: 1981

Answers (3)

stealthyninja
stealthyninja

Reputation: 10371

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.

Upvotes: 1

ipr101
ipr101

Reputation: 24236

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

Upvotes: 2

Doozer Blake
Doozer Blake

Reputation: 7797

It's a Bitwise AND.

    47 is 101111
AND  1 is 000001
        = 000001

while

    46 is 101110
AND  1 is 000001
        = 000000

Upvotes: 9

Related Questions