[AS3] Planning Bytearrays

Subscribe to [AS3] Planning Bytearrays 5 posts

avatar for ErlendHL ErlendHL 1318 posts
Flag Post

Yo, I’m trying to save an array of tiles to a bytearray in the best way possible (less filesize)
So I thought like, byte 1: length of the tile (in bytes), byte2=tiletype, byte3=x, byte4=y, byte5:movetoX, byte6:movetoY (because the tiles can be moveable and have infinite etc…
So I have to plan things before I start and idk if this would totally do it. Is there any useful algorithm of planning or a program or something that would make all this easier? (in the future too)
And do you have any tips regarding defining file syntax?

Thanks!

 
avatar for Drakim Drakim 1183 posts
Flag Post

Your idea of how a bytearray works is slightly wrong, and I think I know why. It’s because the [ ] syntax can be very confusing.

Let’s say I wanted to store some color values in a bytearray.

mybytearray[0] = 0xFF55AA;
mybytearray[1] = 0x003377;

This code is faulty, because unlike a regular array, all of 0xFF55AA doesn’t fit into [0]. It actually spills over into [1] then [2] and so on. So if we tried to read what is inside [0] we would get the wrong result because we partially overwrote it with the second write to [1].

If I remember correctly, an Int takes 4 bytes to store. you would have to do this:

mybytearray[0] = 0xFF55AA;
mybytearray[4] = 0x003377;

There are some methods on the bytearray to simplify reading and writing, but they are slower than the direct [ ] access. But you could always use the easier thing first and swap it back later when you have a better grasp. You can find a list over all the methods here

 
avatar for ErlendHL ErlendHL 1318 posts
Flag Post

Ah, yeah, bytes only have 8 bits… so I will use readInt and writeInt then. So this is what I’ve thought of so far.

b_1 = length
b_2 = number of positions (a position consists of time (to eventually get there), x and y)
3 and 3 bytes from b_3 to b_(b_2 * 3) = positions 
b_(b_2 * 3) to b_(b_1) = text parameter (string)

So here one b is one int. Is this the right way to think?

 
avatar for ErlendHL ErlendHL 1318 posts
Flag Post

BTW is it possible to make a new temporary ByteArray for every tile I’m writing, and then push it to the main ByteArray without having to loop through all the bytes? Cause I don’t know how else I would write the length of the tile (in bytes) before the tile.

i.e. does it work with mainByteArray.writeObject(tempByteArray)?

 
avatar for Drakim Drakim 1183 posts
Flag Post

Yes, there is a method called writeBytes which does pretty much that. Take stuff bytearray1 and write it to bytearray2