Android Code Snippet Swap without extra variable

Here's a reminder that we don't need an extra variable for swapping integer values:
B4X:
Dim a = 120, b = 110 As Byte 'Short / Int / Long
Log(a & " | " & b) 'Output: 120 | 110
a = a + b
b = a - b
a = a - b
Log(a & " | " & b) 'Output: 110 | 120

It works for doubles and floats as well, but you might lose precision (12.2 becomes 12.1999998), so beware.
 

Emme Developer

Well-Known Member
Licensed User
Longtime User
Another way :)
B4X:
Dim a = 120, b = 110 As Byte 'Short / Int / Long
    Log(a & " | " & b) 'Output: 120 | 110
    a = Bit.Xor(a,b)
    b = Bit.Xor(a,b)
    a = Bit.Xor(a,b)
    Log(a & " | " & b) 'Output: 110 | 120
 

wonder

Expert
Licensed User
Longtime User
Another way :)
B4X:
Dim a = 120, b = 110 As Byte 'Short / Int / Long
    Log(a & " | " & b) 'Output: 120 | 110
    a = Bit.Xor(a,b)
    b = Bit.Xor(a,b)
    a = Bit.Xor(a,b)
    Log(a & " | " & b) 'Output: 110 | 120
Can you use it for floats and doubles without loosing precision?
I have no access to B4X right now.
 

Emme Developer

Well-Known Member
Licensed User
Longtime User
Can you use it for floats and doubles without loosing precision?
I have no access to B4X right now.
B4X:
    Dim a = 120.2, b = 110.7 As Float 'Short / Int / Long
    Log(a & " | " & b) 'Output: 120.19999694824219 | 110.69999694824219
    a = Bit.Xor(a,b)
    b = Bit.Xor(a,b)
    a = Bit.Xor(a,b)
    Log(a & " | " & b) 'Output: 110 | 120

This is the log, bit.xor return an int so you lost the decimal values
 

Emme Developer

Well-Known Member
Licensed User
Longtime User
Using strings :p
B4X:
Dim a = "A", b =  "B" As String
Log(a & " | " & b) 'Output: A | B
    a = A&B
    b = A.replace(B,"")
    a = A.replace(B,"")
    Log(a & " | " & b) 'Output: B | A
 
Top