14

Using Bitwise XOR to exchange variable values in ActionScript

 3 years ago
source link: http://www.mikechambers.com/blog/2007/10/22/using-bitwise-xor-to-exchange-variable-values-in-actionscript/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Using Bitwise XOR to exchange variable values in ActionScript

Monday, October 22, 2007

I have been studying some Objective-C in my spare time, and was reading up on Bitwise operators tonight. I came across a simple way to exchange the value of two variables using the Exclusive-OR (XOR) operator that doesn’t require creating a temporary variable.

Normally, if you wanted to exchange the value of two variables, you would have to create a temp variable to store values temporarily (which uses additional memory). For example:

package
{
	import flash.display.Sprite;
	import flash.system.System;

	public class SwitchVariables extends Sprite
	{
		public function SwitchVariables()
		{
			var a:int = 5;
			var b:int = 6;
			var temp:int;
			
			trace("a = " + a + " : b = " + b);
			
			
			temp = a;
			a = b;
			b = temp;
			
			trace("a = " + a + " : b = " + b);
		}
	}
}

Notice that you have to create an additional variable, named temp to temporarily store the value while it is switched.

However, you can use the Bitwise XOR Operator to switch the values without having to create the temporary variable. For example:

package
{
	import flash.display.Sprite;
	import flash.system.System;

	public class SwitchVariables extends Sprite
	{
		public function SwitchVariables()
		{
			var a:int = 5;
			var b:int = 6;
			
			trace("a = " + a + " : b = " + b);
			
			a ^= b;
			b ^= a;
			a ^= b;
			
			trace("a = " + a + " : b = " + b);
		}
	}
}

You can find a good explanation of what the Exclusive OR operator does here and a discussion of the XOR swap algorithm here.

This is probably not needed in most cases (it can make the code a little harder to read), but if you are exchanging the value of variables in a loop and running into memory issues, this might come in handy.

Have any other bitwise operator tips? Post them in the comments.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK