Introduction to ByteArray

Introduction to ByteArray

Tutorial Details
  • Difficulty: Intermediate
  • Platform: Flash (Flash Player 10)
  • Language: AS3
  • Software used: Flash Builder 4
  • Estimated Completion Time: 30 minutes

ByteArray is an extremely powerful Class that can be used for many things related to data manipulation, including (but not limited to) saving game data online, encrypting data, compressing data, and converting a BitmapData object to a PNG or JPG file. In this introduction, we’ll use the ByteArray class to take a native AS3 object and encode it to a string that could be saved to a server for later recovery, then decode it later.

In previous tutorials we’ve seen how to use XML and JSON to encode data in a textual (String) format. However, both XML and JSON are designed to be human-readable, and as a result they’re much longer than they need to be. It can also be tricky to convert certain types of AS3 object to either format. ByteArray has some truly advanced features, but to start with, we’ll just look at one simple one: it makes it very easy to turn an AS3 object into a String.


Final Result Preview

Let’s take a look at the final result we will be working towards:

When you paste an encoded ByteArray string into the TextField and click the Load button, it will decrypt it, and show the object properties saved in it. You can try the following encoded ByteArrays; copy-paste them into the TextField and click the Load button to see what I am talking about:

//This ByteArray will show my data (This is the default ByteArray loaded)
CgsBFW9jY3VwYXRpb24GB0NUTw93ZWJzaXRlBiFodHRwOi8vaWt0LmNvLmlkCW5hbWUGDVRhdWZpawE=
//This ByteArray will show my current thought
CgsBIWZvb2RfZm9yX3Rob3VnaHQGgnVJIGFtIHRoaW5raW5nIG9uIHNoYXJpbmcgdGhlIHRlY2huaXF1ZSBpIHVzZWQgdG8gbWFrZSBhIEZ1bGwgRmxhc2ggRHluYW1pYyBXZWJzaXRlIFNFTyBGcmllbmRseSBmb3IgbXkgbmV4dCBUdXRvcmlhbCBpbiBBY3RpdmVUdXRzKy4uLiA8dT5XaGF0IGRvIHlvdSB0aGluaz88L3U+IDxiPmlzIGl0IGEgZ29vZCBpZGVhPC9iPj8B
//This ByteArray will talk about Flash and SEO and my experience with them
CgsBEXF1ZXN0aW9uBoEDPGI+PHU+Q2FuIGEgZnVsbHkgZHluYW1pYyBGbGFzaCBXZWJzaXRlIGJlIFNFTyBmcmllbmRseTwvdT48L2I+Pz8NYW5zd2VyBoM/SXQgY2FuLCBoZXJlIGlzIHRoZSBwcm9vZiwgPGEgaHJlZj0naHR0cDovL3d3dy5nb29nbGUuY28uaWQvc2VhcmNoP3E9Zmxhc2grc2VvJmllPXV0Zi04Jm9lPXV0Zi04JmFxPXQnIHRhcmdldD0nX2JsYW5rJz5odHRwOi8vd3d3Lmdvb2dsZS5jby5pZC9zZWFyY2g/cT1mbGFzaCtzZW8maWU9dXRmLTgmb2U9dXRmLTgmYXE9dDwvYT4sIGlrdC5jby5pZCBpcyByYW5rZWQgIzYgb3ZlciB0aGVyZQE=

Step 1: Create New ActionScript Project

Create New ActionScript Project

Within the ‘Flash Builder’ window :

  1. Open Flash Builder 4
  2. Click the File Menu
  3. Hover to New
  4. Click ActionScript Project

Step 2: New ActonScript Project Setup

ActionScript Project Setup

Within the ‘New ActionScript Project’ window :

  1. Type ‘TUTORIAL_ByteArray’ into Project name field
  2. Please remember where you save your project
  3. Click ‘Finish’ button

Step 3: Base64.as

Copy Base64.as into your project ‘com’ directory.

Copy Base64.as file into 'com' directory
  1. Create a new ‘com’ directory inside your source directory.
  2. Download the Base64.as file from the source download.
  3. Put the file into the newly created ‘com’ directory.

Base64.as will come in useful later. It’s by Steve Webster, who used to reside at dynamicflash.com (he left the Flash community a couple of years ago).


Step 4: Necessary Classes

Import all Classes used in this project

In TUTORIAL_ByteArray class (which is the main class), please import the following Classes for this tutorial:

package
{
	import flash.display.Sprite;
	import flash.text.TextField;
	import flash.text.TextFieldType;
	import flash.text.TextFieldAutoSize;
	import flash.text.TextFormat;
	import flash.events.MouseEvent;
	import flash.utils.ByteArray;
	import com.Base64;

	public class TUTORIAL_ByteArray extends Sprite
	{
		public function TUTORIAL_ByteArray()
		{

		}
	}
}

Step 5: Getting used to Flash Builder I

Trace the 'Hello World' message

Add the following code inside TUTORIAL_ByteArray Constructor for a very simple test.

public function TUTORIAL_ByteArray()
{
	var _test:String = "Hello world!";
	trace(_test);
}

Press F11 key to run this project, you should get the message inside the Console Window.


Step 6: Getting used to Flash Builder II

Local variable only available inside the function it is created

Now let’s try to trace the message inside _test variable, but this time we will do it from another function:

public function TUTORIAL_ByteArray()
{
	var _test:String = "Hello world!";
	TestFunction();
}
private function TestFunction():void{
	trace(_test);
}

Press CTRL+S to save your project. An error detected after you saved your project; this is because a variable which has been declared inside a function will not be available for any other function. So for this case, we need to declare the _test variable outside:

public function TUTORIAL_ByteArray()
{
	TestFunction();
}
private function TestFunction():void{
	trace(_test);
}
private var _test:String = "Hello world!";
Private variables are available to all function inside the same class

Step 7: Necessary Private Variables

Create all private variables for this project

Please add the following private variables for this project:

public function TUTORIAL_ByteArray()
{
	TestFunction();
}
private function TestFunction():void{
	trace(_test);
}
private var _test:String = "Hello World!";
private var _loadButton:TextField;
private var _inputField:TextField;
private var _testObject:Object;
private var _testByteArray:ByteArray;

Step 8: UI

Let’s create a simple user interface for this project.

a Simple user interface

Now that we need to display something into our project, we need to declare our stage sizes (Check Line 13).

Rename our TestFunction into InitUI function, and put the following line of codes inside. Please read the explanation commented inside the code.

[SWF(width="550", height="400", frameRate="60", pageTitle="Tutorial ByteArray")]
public class TUTORIAL_ByteArray extends Sprite
{
	public function TUTORIAL_ByteArray()
	{
		InitUI();
	}
	private function InitUI():void{
		//Initialize our TextFields so that we can use them
		_loadButton = new TextField();
		_inputField = new TextField();

		//Give a defaultTextFormat for both of them (Tahoma at 11pt, colored 0x777777)
		_loadButton.defaultTextFormat = _inputField.defaultTextFormat = new TextFormat("Tahoma", 11, 0x777777);

		//Give both of them a border
		_loadButton.border = _inputField.border = true;

		//Set the autosize for our Load Button , so that it will automatically shrink / grow to fit the text inside
		_loadButton.autoSize = TextFieldAutoSize.LEFT;

		//Set the selectable of our Load Button to false, so that user cannot select the text in it
		_loadButton.selectable = false;

		//Set the multiline and wordWrap of our Input Field to true, so that a long text will automatically wrapped to the next line
		_inputField.multiline = _inputField.wordWrap = true;

		//Enable user to type something into our Input Field, by setting this type property
		_inputField.type = TextFieldType.INPUT;

		//Put some text into Both of them
		_loadButton.text = "Load";
		_inputField.text = "";

		//Add both of them into stage, so that they are visible to our visitors
		addChild(_inputField);
		addChild(_loadButton);

		//Position our Input Field and make it bigger
		_inputField.x = 25;
		_inputField.y = 25;
		_inputField.width = 200;
		_inputField.height = 150;

		//There is a reason why i did this, so that the Load Button is located directly below our Input Field
		//So you can position the Input Field anywhere you like, as long as there is this code, the Load Button will stick below the Input Field
		_loadButton.y = _inputField.y + _inputField.height;
		_loadButton.x = _inputField.x;
	}

Press F11 to run this project and see the simple user interface we have created.


Step 9: Enable Interactivity

Type into the field and click the load button

Please read the explanation commented inside the code

	_loadButton.y = _inputField.y + _inputField.height;
	_loadButton.x = _inputField.x;

	//Add an Event Listener for our _loadButton, so whenever the user clicks this button,
	//Flash will call _loadButton_CLICK() Method
	_loadButton.addEventListener(MouseEvent.CLICK, _loadButton_CLICK, false, 0, true);
}
//This method will be called whenever user click the _loadButton
private function _loadButton_CLICK(Events:MouseEvent = null):void{
	//Get anything that the user input and save them into our _test variable
	_test = _inputField.text;

	//Trace the _test variable
	trace("User input the following message : " + _test);
}

Press F11 to run this project; try typing something into the _inputField and then click the _loadButton. This is the most basic technique of getting a variable from our user and storing it into our private variable.


Food for Thought

We have finally reach our most important steps in this project, but before we continue let me provides a mental stimulus for thinking. Currently in our project, we are capable of getting a String and storing it in our private variable. But it is only a string; how about if I want a user to type in something inside _inputField so that I can get an Object from it? What should the user type? The answer is an ‘Encoded Base64 ByteArray’


Step 10: Introduction to ByteArray

Output from our ByteArray

We will proceed slowly this time, so that you will understand the ByteArray class and be able to create your own data manipulation and apply it to your own projects. Please read the explanation commented inside the code:

public function TUTORIAL_ByteArray()
{
	InitUI();
	CreateByteArray();
}
private function CreateByteArray():void{
	//Initialize our _testObject variable, so that we can populate many dynamic properties and store String data in it (we will load them later whenever user clicked the _loadButton)
	_testObject = new Object();
	_testObject.name = "Taufik";
	_testObject.website = "<a href='http://ikt.co.id'>http://ikt.co.id</a>";
	_testObject.occupation = "CTO";

	//Initialize our _byteArray variable, so that we can start converting object into a ByteArray
	_testByteArray = new ByteArray();

	//Convert the Object into Byte Array, This is how you do it, to convert an Object into a ByteArray, IT IS SIMPLE isnt it? :))
	_testByteArray.writeObject(_testObject);

	//Lets see if everything works properly
	trace("Our first ByteArray created :: " + _testByteArray.toString());
}

Press F11 to run this project. See how simple it is, this ByteArray is an extremely powerful class and yet it is not hard at all. We’ve taken a native AS3 Object and converted it to Action Message Format.

Before sending the data to our PHP Script using the GET method, we should convert it into a Base64 String. This is because Base64 can be carried by XML (and by HTML).


Step 11: Encoding ByteArray into Base64 String

a Base64 String representation of our Byte data

Please read the explanation commented within the code.

private function CreateByteArray():void{
	//Initialize our _testObject variable, so that we can populate many dynamic properties and store String data in it
	//(we will load them later whenever user clicks the _loadButton)
	_testObject = new Object();
	_testObject.name = "Taufik";
	_testObject.website = "<a href='http://ikt.co.id'>http://ikt.co.id</a>";
	_testObject.occupation = "CTO";

	//Initialize our _byteArray variable, so that we can start converting object into a ByteArray
	_testByteArray = new ByteArray();

	//Convert the Object into Byte Array, This is how you do it, to convert an Object into a ByteArray, IT IS SIMPLE isnt it? :))
	_testByteArray.writeObject(_testObject);

	//Encode the ByteArray into Base64 String (so that we can send them via PHP or copy the text to notepad), again IT IS VERY SIMPLE!
	var encoded:String = Base64.encodeByteArray(_testByteArray);

	//Put the encoded Base64 String into our _inputField (so that we can copy them into notepad)
	_inputField.text = encoded;
}

Press F11 to run this project. If converting an Object into a ByteArray is simple, converting the Byte value of our data into Base64 String is as simple, thanks to Base64.as.


Step 12: Converting Encoded Base64 String into Object

Converting a Base64 String into Object and displaying its properties and values

We will try to decode the entered Base64 String into an Object whenever the user clicks the _loadButton, change our _loadButton_CLICK function. Please read the explanation commented inside the code:

private function _loadButton_CLICK(Events:MouseEvent = null):void{
	//We have to catch any Errors
	try{
		//We decode our encoded Base64 String into a ByteArray, so that we can retrieve our Object back
		var DecodedByteArray:ByteArray = Base64.decodeToByteArray(_inputField.text);

		//If converting an Object into ByteArray is simple, retrieving an Object from ByteArray is as simple as this
		var LoadedObject:Object = DecodedByteArray.readObject();

		//Prepare to output all properties and their values inside the LoadedObject
		var Output:String = "";
		for (var VarName:String in LoadedObject){
			Output += VarName + " : " + LoadedObject[VarName] + "<br>";
		} 

		//Output them into our _inputField
		_inputField.htmlText = Output;
	}catch(err:Error){
		_inputField.text = "Please input an Encoded ByteArray into this TextField before clicking the 'Load' Button. Error message :: " + err.message;
	}
}

Press F11 to run this project. We get our encoded Base64 String of our _testObject inside our _inputField; click the _loadButton to see our project convert this Base64 String back and display all of its properties and values. You can try to copy and paste the Base64 Strings at the beginning of this tutorial and read all of my messages.


Conclusion

The ByteArray Class is an extremely powerful Class, and yet it is very simple to use. I have seen many great Flash apps out there utilizing this ByteArray to perform so many mind blowing data manipulation, such as those kinds I mentioned at the beginning of this tutorial. I have heard many Flash game programmers utilize XML to save their visitors’ ‘Save Game Data’, but as we all already know, XML is one hell of a very complicated class; with ByteArray I can save something like this EASILY.

private function CreateByteArray():void{
	_testObject = new Object();
	_testObject.name = "Taufik";
	_testObject.website = "<a href='http://ikt.co.id'>http://ikt.co.id</a>";
	_testObject.occupation = "CTO";
	_testObject.level = 99;

	//Get the state of this Game Character Inventory
	var _inventory:Array = new Array({item_id:5, amount:1}, {item_id:85, amount:1}, {item_id:42, amount:5});
	_testObject.inventory = _inventory;

	//Get what is the skill they already level up
	var _skill:Array = new Array({skill_id:1, level:0}, {skill_id:2, level:1});
	_testObject.skill = _skill;

	//Initialize our _byteArray variable, so that we can start converting object into a ByteArray
	_testByteArray = new ByteArray();

	//Convert the Object into Byte Array, This is how you do it, to convert an Object into a ByteArray, IT IS SIMPLE isnt it? :))
	_testByteArray.writeObject(_testObject);

	//Encode the ByteArray into Base64 String (so that we can send them via PHP or copy the text to notepad), again IT IS VERY SIMPLE!
	var encoded:String = Base64.encodeByteArray(_testByteArray);

	//Put the encoded Base64 String into our _inputField (so that we can copy them into notepad)
	_inputField.text = encoded;
}

Yeah, something this complicated only takes a couple line of codes, imagine the horror of saving this data using XML and retrieving them back for further use. All in all I have to say that with Byte data manipulation you can achieve a lot of things, and some might be the solution you have been looking for all this time.

I hope you have found this tutorial useful. Thanks for reading!

Add Comment

Discussion 5 Comments

  1. Mike Skramstad says:

    So thanks for the tutorial–well explained !

    I guess I’m not fully understanding the use cases for the ByteArray. It allows you to create an Object with a number of fields and save it as a single encoded string. And then I can take this String and send it to PHP for saving into a SQL Database in a single field. Then later I can pull all the data back using the decode feature ? As opposed to sending out all fields to PHP separately and then loading them in separately ?

    What other uses are there to ByteArray? It’s an abstract class and I’ve never used it in any projects because of a lack of clarity of its purpose. Thanks for your tutorial..

    • Raweden says:

      The usage of ByteArray is kind of unclear in this tutorial. Yes The ByteArray class is abstract and can have many usages. The two most primary usages is to allow flash create object from formats that is natively cant read, one example of this is the Bitmap Image encoder in the tutorial of Lee Brimelow. I have self also used the ByteArray in this purpose when porting the two most popular icon formats to flash.

      Another usage is that you can register classes to be used with ByteArra.writeObject(), so you can control how your own classes are encoded and decoded by reading and writing the object to the ByteArray. i have never testet it myself but flex uses this to write ArrayCollection objects to a bytearray.

  2. Bob Howard says:

    If you want more in depth information about ByteArrays, check out this link: http://www.bytearray.org/?p=711 Only the first two chapters are written, but there is still a lot of good information.

  3. pejman says:

    Thanks for your help

  4. Riccardo says:

    Nice tutorial. Really useful stuff for flash games. Thanks

Add a Comment

To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.