user1014540
user1014540

Reputation: 23

AS3 ByteArray readShort

i have to read a sequence of bytes,that was written in different ways (writeBite, writeShort and writeMultiByte) and display them has list of HEX byte on video. My problem is convert the number 1500, i tryed other number and the results was correct... here is a an example:

var bytes:Array = [];
var ba:ByteArray = new ByteArray();
ba.writeShort(1500);

ba.position = 0;

for (var i=0; i<ba.length; i++)
{
   bytes.push(ba.readByte().toString(16));
}
trace(bytes);//5,-24 i'm expetting 5,DC

Upvotes: 1

Views: 1485

Answers (2)

kapex
kapex

Reputation: 29999

The method readByte reads a signed byte (ranges from -128 to 127). The most significant bit defines the sign. In case of numbers greater than 127 (like DC) that bit will be 1 and the number will be seen as a negative number. The two's complement of the negative byte is used to get the signed value. In case of DC, which is 1101 1100 in binary the complement would be 0010 0011 which is 23. A one is added and the value will be regarded as negative, which will give you the -24 you are seeing.

You should use readUnsignedByte to read values from 0 to 255.

Upvotes: 1

Joan Charmant
Joan Charmant

Reputation: 2031

As there is no real Byte type in AS3, readByte() returns an int. You can try this instead:

for (var i=0; i<ba.length; i++)
{
    bytes.push(ba[i].toString(16));
}

Upvotes: 0

Related Questions