Using bit fields in ActionScript 3
Update: I just confirmed with the player team that a Boolean actually takes up 4 bytes.
I’ve been doing a lot of research lately on different uses for ByteArrays. This is in preparation for my ByteArrays for Beginners session that I will be doing at FITC Toronto. While in Amsterdam recently, Thibault Imbert of bytearray.org mentioned how he uses bit fields in WiiFlash to make boolean values as small as possible. Basically when the WiiFlash server sends over the state of the Wiimote buttons to Flash, it sends over a single byte where each bit represents the state of a particular button.
So why would you want to do this? Well if you have eight boolean values it would take up 32 bytes of space if you use the native Boolean class, as each one takes up 4 bytes. But in reality that is 32 times as big as it needs to be. If you set each bit of a single byte to either 1 or 0 based on your boolean values it will only take up a single byte. Now this is not going to be worth it for most situations, but if you need really high-speed binary communication than it will be more efficient. Below is an example of how you could pack eight booleans into a single byte:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | var ba:ByteArray = new ByteArray(); var bf:uint = 0; bf = 1<<7; //Set bit 8 to true bf |= 1<<6; //Set bit 7 to true bf |= 0<<5; //Set bit 6 to false bf |= 1<<4; //Set bit 5 to true bf |= 1<<3; //Set bit 4 to true bf |= 1<<2; //Set bit 3 to true bf |= 1<<1; //Set bit 2 to true bf |= 1; //Set bit 1 to true ba.writeByte(bf); trace(ba[0].toString(2)); //11011111 |
In the above code all of the boolean values are set to true except for bit number 6. This way of setting individual bits is probably the easiest to read, at least for me. Now when you want to retrieve the value of an individual bit you can simply do an AND on the byte like I do below.
1 | if(ba[0]&32) trace("Bit 6 is true"); //Won't trace anything |
The reason I chose the number 32 is that it is the perfect binary mask to retrieve the 6th bit of the byte. In binary the number 32 is represented as 00100000. I will go over this more during my session and will also do a tutorial on it soon.
Lee




