Jeff Reed
Jeff Reed

Reputation: 231

How do I use Xor in VB without using the built-in one?

I want to use Xor without using the built-in one in Visual Basic .NET

Xor description:

It is the logical as well as bitwise Logical Exclusive OR operator.

It returns True if both expressions are True or both expressions are False; otherwise it returns False.

This operator does not perform short-circuiting, it always evaluates both expressions and there is no short-circuiting counterpart of this operator

Is this even possible? And if so, how?

Upvotes: 0

Views: 946

Answers (4)

NativeBasic
NativeBasic

Reputation: 1

Dim val1, val2 As Boolean If Val1 <> Val2 Return False Else Return True End If

'That is XNOR

Upvotes: 0

dbasnett
dbasnett

Reputation: 11773

The definition stated for XOR is incorrect, as other have noted. XOR is simply addition without carry.

    Dim b1 As Boolean = False
    Dim b2 As Boolean = False

    For x As Integer = 1 To 2
        For y As Integer = 1 To 2
            Dim n1 As Integer = CInt(b1)
            Dim n2 As Integer = CInt(b2)
            Dim ans As Boolean = CBool((n1 + n2) And 1) 'add, ignore carries
            Debug.WriteLine("b1 {0}  b2 {1}   ans {2}", b1, b2, ans)
            b2 = Not b2
        Next
        b1 = Not b1
    Next

Upvotes: 0

Stephen Cook
Stephen Cook

Reputation: 181

XOR is simply a logical operation. If you wanted, you could replace it entirely with NANDs, since NAND is functionally complete.

XOR could be

(a and not b) or (not a and b)

or

(a or b) and (not a or not b)

or if you don't want logical operators at all...

If(a) Then
    If(not b) Then
        Return True
    End If
Else If(not a) Then
    If(b) Then
        Return True
    End If
End If
Return False

So basically, yes - I imagine there are a myriad of ways that you could do this. But I can't think of why you would ever want to.

Upvotes: 2

clcto
clcto

Reputation: 9648

I believe that definition is not correct. Exclusive OR means that one and only one of the expressions are true. That definition is Exclusive NOR.

But anyway

XOR:
(bool1 and not bool2) or (not bool1 and bool2)

XNOR:
(bool1 and bool2) or (not bool1 and not bool2)

Or even simply

bool1 = bool2

Upvotes: 0

Related Questions