XOR swap in VB.NET

This article containing a method of swapping of two integer in Visual basic .NET
  • 2789
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


    Imports System.Collections
    Public Class values
        Public Shared Sub Main()
            Dim FirstNo As Integer
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)
        End Sub




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. 


More Articles

© 2020 DotNetHeaven. All rights reserved.