Posts Tagged ‘ByteArray’
Unexpected ByteArray behavior
Yesterday I stumbled upon really unexpected ByteArray behavior with reading Strings containing Null characters or simply speaking characters with ASCII code zero. Here’s the code:
var s:String = "a" + String.fromCharCode( 0 ) + "b" + String.fromCharCode( 0 );
trace( s.length ); // 4
trace( s.charCodeAt(0), s.charCodeAt(1), s.charCodeAt(2), s.charCodeAt(3) ); // 97 0 98 0
var bytes:ByteArray = new ByteArray();
bytes.writeUTF( s );
bytes.writeUTFBytes( s );
trace( "bytes:", bytes.length );
bytes.position = 0;
while ( bytes.bytesAvailable ) {
trace( "-", bytes.readUnsignedByte() );
}
// 0
// 4
// 97
// 0
// 98
// 0
// 97
// 0
// 98
// 0
bytes.position = 0;
s = bytes.readUTF();
trace( s.length ); // 1
trace( s.charCodeAt(0), s.charCodeAt(1), s.charCodeAt(2), s.charCodeAt(3) ); // 97 NaN NaN NaN
s = bytes.readUTFBytes(4);
trace( s.length ); // 1
trace( s.charCodeAt(0), s.charCodeAt(1), s.charCodeAt(2), s.charCodeAt(3) ); // 97 NaN NaN NaN
Or you can run this at wonderfl.
As you can see ActionScript is perfectly OK with Strings containing \x00. They are even written correctly but couldn’t be read right. I would say that this is unexpected behavior. One can say that in many languages (like C for example) Null characters are used to indicate the end of a string. But here we explicitly write its length into ByteArray. The only logical explanation I have is that this length is used only to read certain amount of bytes not less not more. After that while bytes are traveling from ByteArray to a new String object they are passing some internal representation in Flash Player / AVM2 which indeed is a Null-terminated string. Which crops our string at Null character.
Now I have to store data a bit differently in a more complex way. Being able to dump strings into ByteArrays is essential for me.
Continue Reading | No Comments
Tags: AVM2, Bug, ByteArray, Null character, String
Where’s my byte, dude??!
While working on his famous library blooddy stuck upon what appeared to be a flash bug. Sometimes an empty ByteArray is not THAT empty at all.
Basically if you write something to it first you can get non-zero bytes in your new ByteArray other than you just wrote yourself.
bytes.writeUnsignedInt( 10 ); bytes.length = LENGTH;
But if you set the length first everything runs smoothly. Be careful!
Great image distortion idea
Recently I wrote about my distortion effect. Believe me, I experimented with it a lot. And it was damn slow on big bitmaps. But here’s a funny way to do it through native jpeg decoding. And it runs smooth on relatively big bitmaps. The guy messes up with jpeg data in ByteArray many times in a row loading it over and over again. Letting Flash native jpeg decoder do the work for him. This is is a great example of creative thinking!
Continue Reading | No Comments
Tags: ByteArray, Distortion, Effect, JPEG
