XOR swap in VB.NET

This article containing a method of swapping of two integer in Visual basic .NET
  • 2611
In programming language we say the XOR swap is a algorithm which is used XOR bitwise operator to swap the values of two variables having the same data type. Now you think that if  conventional swapping is also available in Vb.Net than what is need of XOR swapping. So, the answer is that, whenever you use conventional swapping you requires the use of a temporary storage variable, for that reason XOR swapping is introduced there is no need to take any extra variable in XOR swapping.

The algoritham or syntex we can say of XOR swap is:

X : = X  XOR  Y
Y : = X  XOR  Y
X : = X  XOR  Y

EXAMPLE CODE

    Imports System.Collections
    Public Class values
        Public Shared Sub Main()
            Dim FirstNo As Integer
            Dim
SecondNo As Integer
            FirstNo = 50
            SecondNo = 70
            Console.WriteLine("Before swap: {0}, {1}", FirstNo, SecondNo)
            FirstNo = FirstNo Xor SecondNo
            SecondNo = FirstNo Xor SecondNo
            FirstNo = FirstNo Xor SecondNo
            Console.WriteLine("After swap: {0}, {1}", FirstNo, SecondNo)
            Console.ReadLine()
        End Sub
    End
Class

OUTPUT

16.gif
 

SUMMARY

In above this article XOR algorithm having three machine code instructions and XOR is a commutative operation. I hope when you need to perform swapping this article helps you a lot. 

Categories

More Articles

© 2019 DotNetHeaven. All rights reserved.