views:

58

answers:

1

In the following code:

var bytes:ByteArray = new ByteArray();

var i:int = -1;
var j:int;

bytes[0] = i;    // bytes[0] = -1 == 0xff
j = bytes[0];    // j == 255;

The int j ends up with value 255, rather than -1. I can't seem to find a document defining how indexed access to a ByteArray is supposed to be sign extended - can I reliably assume this behavior, or should I take steps to truncate such values to 8 bit quantities? I'm porting a bunch of code from Java and would prefer to use the indexed access rather that the readByte() etc methods.

A: 

The IDataInput interface (implemented by ByteArray) says:

Sign extension matters only when you read data, not when you write it. Therefore you do not need separate write methods to work with IDataInput.readUnsignedByte() and IDataInput.readUnsignedShort().

The same would naturally apply to [] array access, so you wouldn't need to truncate before writing.

I can't see any explicit documentation of that, and nothing that states that array read access is unsigned. If you wanted to ensure that read access gave you an unsigned value back you could say:

j= j<<24>>>24;

and similarly with >> for signed. However with ActionScript being a single implementation, not a general standard, you probably don't have to worry about it

bobince
Thanks for the response. Nice to get some confirmation that this (reading using [] operator into an int) is indeed "undefined". Not a huge deal to workaround, perhaps a future update will clarify the behavior in the docs.
Steve Wetherill