Reversing primitives without creating a temp

I’ve been working my way through a load of practise challenges recently to make sure I’m keeping my brain active and I worked out a way of swapping two primitive values without the overhead of creating a third value to use as a temporary storage value.

Lets say you have two characters, to swap them you would execute a series of binary XORs:

	char charOne = 'i';
	char charTwo = 'H';

	charOne ^= charTwo;
	charTwo ^= charOne;
	charOne ^= charTwo;

	System.out.println(String.valueOf(new char[] {charOne, charTwo}));

you would get an output of ‘Hi’.

Note that

charOne ^= charTwo;

is the shorthand version of

charOne = (char) (charOne ^ charTwo);

If you have a look at what’s happening: charOne is ‘i’ which is 1101001 in binary and charTwo is ‘H’ which is 1001000 in binary.

First we XOR the two values and assign back to charOne:

charOne: 1 1 0 1 0 0 1
charTwo: 1 0 0 1 0 0 0
charOne: 0 1 0 0 0 0 1

charOne is reassigned the binary representation of 0100001.

We then XOR the new value of charOne with the initial value of charTwo and assign to charTwo:

charTwo: 1 0 0 1 0 0 0
charOne: 0 1 0 0 0 0 1
charTwo: 1 1 0 1 0 0 1

so now charTwo has a binary representation of 1101001, which was the initial value of charOne.

we then XOR the third time and assign back to charOne:

charOne: 0 1 0 0 0 0 1
charTwo: 1 1 0 1 0 0 1
charOne: 1 0 0 1 0 0 0

and we see that the binary representations of the two characters have swapped.

Just thought that was a pretty nice way of doing it.

Leave a Reply