1. Code
  2. JavaScript

Introduction to ByteArray

Scroll to top

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:

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

Step 1: Create New ActionScript Project

Create New ActionScript ProjectCreate New ActionScript ProjectCreate 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 SetupActionScript Project SetupActionScript 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' directoryCopy Base64.as file into 'com' directoryCopy 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 projectImport all Classes used in this projectImport all Classes used in this project

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

1
2
package
3
{
4
	import flash.display.Sprite;
5
	import flash.text.TextField;
6
	import flash.text.TextFieldType;
7
	import flash.text.TextFieldAutoSize;
8
	import flash.text.TextFormat;
9
	import flash.events.MouseEvent;
10
	import flash.utils.ByteArray;
11
	import com.Base64;
12
	
13
	public class TUTORIAL_ByteArray extends Sprite
14
	{
15
		public function TUTORIAL_ByteArray()
16
		{
17
			
18
		}
19
	}
20
}

Step 5: Getting used to Flash Builder I

Trace the 'Hello World' messageTrace the 'Hello World' messageTrace the 'Hello World' message

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

1
2
public function TUTORIAL_ByteArray()
3
{
4
	var _test:String = "Hello world!";
5
	trace(_test);
6
}

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 createdLocal variable only available inside the function it is createdLocal 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:

1
2
public function TUTORIAL_ByteArray()
3
{
4
	var _test:String = "Hello world!";
5
	TestFunction();
6
}
7
private function TestFunction():void{
8
	trace(_test);
9
}

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:

1
2
public function TUTORIAL_ByteArray()
3
{
4
	TestFunction();
5
}
6
private function TestFunction():void{
7
	trace(_test);
8
}
9
private var _test:String = "Hello world!";
Private variables are available to all function inside the same classPrivate variables are available to all function inside the same classPrivate variables are available to all function inside the same class

Step 7: Necessary Private Variables

Create all private variables for this projectCreate all private variables for this projectCreate all private variables for this project

Please add the following private variables for this project:

1
2
public function TUTORIAL_ByteArray()
3
{
4
	TestFunction();
5
}
6
private function TestFunction():void{
7
	trace(_test);
8
}
9
private var _test:String = "Hello World!";
10
private var _loadButton:TextField;
11
private var _inputField:TextField;
12
private var _testObject:Object;
13
private var _testByteArray:ByteArray;

Step 8: UI

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

a Simple user interfacea Simple user interfacea 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.

1
2
[SWF(width="550", height="400", frameRate="60", pageTitle="Tutorial ByteArray")]
3
public class TUTORIAL_ByteArray extends Sprite
4
{
5
	public function TUTORIAL_ByteArray()
6
	{
7
		InitUI();
8
	}
9
	private function InitUI():void{
10
		//Initialize our TextFields so that we can use them

11
		_loadButton = new TextField();
12
		_inputField = new TextField();
13
		
14
		//Give a defaultTextFormat for both of them (Tahoma at 11pt, colored 0x777777)

15
		_loadButton.defaultTextFormat = _inputField.defaultTextFormat = new TextFormat("Tahoma", 11, 0x777777);
16
		
17
		//Give both of them a border 

18
		_loadButton.border = _inputField.border = true;
19
		
20
		//Set the autosize for our Load Button , so that it will automatically shrink / grow to fit the text inside

21
		_loadButton.autoSize = TextFieldAutoSize.LEFT;
22
		
23
		//Set the selectable of our Load Button to false, so that user cannot select the text in it

24
		_loadButton.selectable = false;
25
		
26
		//Set the multiline and wordWrap of our Input Field to true, so that a long text will automatically wrapped to the next line

27
		_inputField.multiline = _inputField.wordWrap = true;
28
		
29
		//Enable user to type something into our Input Field, by setting this type property 

30
		_inputField.type = TextFieldType.INPUT;
31
		
32
		//Put some text into Both of them

33
		_loadButton.text = "Load";
34
		_inputField.text = "";
35
		
36
		//Add both of them into stage, so that they are visible to our visitors

37
		addChild(_inputField);
38
		addChild(_loadButton);
39
		
40
		//Position our Input Field and make it bigger 

41
		_inputField.x = 25;
42
		_inputField.y = 25;
43
		_inputField.width = 200;
44
		_inputField.height = 150;
45
		
46
		//There is a reason why i did this, so that the Load Button is located directly below our Input Field

47
		//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

48
		_loadButton.y = _inputField.y + _inputField.height;
49
		_loadButton.x = _inputField.x;
50
	}

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 buttonType into the field and click the load buttonType into the field and click the load button

Please read the explanation commented inside the code

1
2
	_loadButton.y = _inputField.y + _inputField.height;
3
	_loadButton.x = _inputField.x;
4
	
5
	//Add an Event Listener for our _loadButton, so whenever the user clicks this button, 

6
	//Flash will call _loadButton_CLICK() Method

7
	_loadButton.addEventListener(MouseEvent.CLICK, _loadButton_CLICK, false, 0, true);
8
}
9
//This method will be called whenever user click the _loadButton

10
private function _loadButton_CLICK(Events:MouseEvent = null):void{
11
	//Get anything that the user input and save them into our _test variable

12
	_test = _inputField.text;
13
	
14
	//Trace the _test variable

15
	trace("User input the following message : " + _test);
16
}

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 ByteArrayOutput from our ByteArrayOutput 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:

1
2
public function TUTORIAL_ByteArray()
3
{
4
	InitUI();
5
	CreateByteArray();
6
}
7
private function CreateByteArray():void{
8
	//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)

9
	_testObject = new Object();
10
	_testObject.name = "Taufik";
11
	_testObject.website = "<a href='https://ikt.co.id'>http://ikt.co.id</a>";
12
	_testObject.occupation = "CTO";
13
	
14
	//Initialize our _byteArray variable, so that we can start converting object into a ByteArray

15
	_testByteArray = new ByteArray();
16
	
17
	//Convert the Object into Byte Array, This is how you do it, to convert an Object into a ByteArray, IT IS SIMPLE isnt it? :))

18
	_testByteArray.writeObject(_testObject);
19
	
20
	//Lets see if everything works properly

21
	trace("Our first ByteArray created :: " + _testByteArray.toString());
22
}

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 dataa Base64 String representation of our Byte dataa Base64 String representation of our Byte data

Please read the explanation commented within the code.

1
2
private function CreateByteArray():void{
3
	//Initialize our _testObject variable, so that we can populate many dynamic properties and store String data in it 

4
	//(we will load them later whenever user clicks the _loadButton)

5
	_testObject = new Object();
6
	_testObject.name = "Taufik";
7
	_testObject.website = "<a href='http://ikt.co.id'>http://ikt.co.id</a>";
8
	_testObject.occupation = "CTO";
9
	
10
	//Initialize our _byteArray variable, so that we can start converting object into a ByteArray

11
	_testByteArray = new ByteArray();
12
	
13
	//Convert the Object into Byte Array, This is how you do it, to convert an Object into a ByteArray, IT IS SIMPLE isnt it? :))

14
	_testByteArray.writeObject(_testObject);
15
	
16
	//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!

17
	var encoded:String = Base64.encodeByteArray(_testByteArray);
18
	
19
	//Put the encoded Base64 String into our _inputField (so that we can copy them into notepad)

20
	_inputField.text = encoded;
21
}

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 valuesConverting a Base64 String into Object and displaying its properties and valuesConverting 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:

1
2
private function _loadButton_CLICK(Events:MouseEvent = null):void{
3
	//We have to catch any Errors

4
	try{
5
		//We decode our encoded Base64 String into a ByteArray, so that we can retrieve our Object back

6
		var DecodedByteArray:ByteArray = Base64.decodeToByteArray(_inputField.text);
7
		
8
		//If converting an Object into ByteArray is simple, retrieving an Object from ByteArray is as simple as this

9
		var LoadedObject:Object = DecodedByteArray.readObject();
10
		
11
		//Prepare to output all properties and their values inside the LoadedObject

12
		var Output:String = "";
13
		for (var VarName:String in LoadedObject){
14
			Output += VarName + " : " + LoadedObject[VarName] + "<br>";
15
		} 
16
		
17
		//Output them into our _inputField 

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

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.

1
2
private function CreateByteArray():void{
3
	_testObject = new Object();
4
	_testObject.name = "Taufik";
5
	_testObject.website = "<a href='http://ikt.co.id'>http://ikt.co.id</a>";
6
	_testObject.occupation = "CTO";
7
	_testObject.level = 99;
8
	
9
	//Get the state of this Game Character Inventory

10
	var _inventory:Array = new Array({item_id:5, amount:1}, {item_id:85, amount:1}, {item_id:42, amount:5});
11
	_testObject.inventory = _inventory;
12
	
13
	//Get what is the skill they already level up

14
	var _skill:Array = new Array({skill_id:1, level:0}, {skill_id:2, level:1});
15
	_testObject.skill = _skill;
16
	
17
	//Initialize our _byteArray variable, so that we can start converting object into a ByteArray

18
	_testByteArray = new ByteArray();
19
	
20
	//Convert the Object into Byte Array, This is how you do it, to convert an Object into a ByteArray, IT IS SIMPLE isnt it? :))

21
	_testByteArray.writeObject(_testObject);
22
	
23
	//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!

24
	var encoded:String = Base64.encodeByteArray(_testByteArray);
25
	
26
	//Put the encoded Base64 String into our _inputField (so that we can copy them into notepad)

27
	_inputField.text = encoded;
28
}

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!

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.