This is for anyone who’s having hair-tearing issues with working with binary data in Flash or Flex, or for those who want to be working with it.
Firstly, embedding binary data
How to embed? Check this article on embedding binary data at dispatchevent.org. For those in a hurry, this is what I took away from it:
[Embed(source="relative_or_absolute_path_to_my_data_file.dat",
mimeType="application/octet-stream")]
private static var __PuzzleData:Class; // This class object constructs a ByteArray subclass
protected static var data:ByteArray = new __PuzzleData(); // statically constructs an instance
...
// Example usage of the embedded byte array
public function getPuzzle(puzzleNumber:int):void {
// set the data ByteArray to the start of the puzzle
data.position = puzzleNumber * PUZZLE_BYTE_SIZE;
// let the puzzle stream its data from the byte array using read*() calls
var puzzle:Puzzle = new Puzzle(data);
return puzzle;
}
Endianness in Flash
There’s one more thing you might need to take special notice of if you’re reading multi-byte numbers, which most numbers are. That is to note which Endian the data is formatted in.
The Endianness of a number is simply the order that its bytes are recorded in the file (or transmitted over the network). As far as I understand it, most compiled programs running on x86 hardware that write numbers to a file do so in “Little Endian” format, which means they write the least significant bytes first. Flash’s default Endianness is “Big Endian”, which expects the most significant bytes first, because that’s the standard endianness for network transmission.
So if your data file seems corrupted when you read it in Flash/Flex, this is very possibly the reason. Setting the Endianness is done on a per-ByteArray level:
myFancyByteArray.endian = Endian.LITTLE_ENDIAN; // set the reads/writes to use little endian