Skip to content

Instantly share code, notes, and snippets.

@lynxerzhang
Last active October 3, 2015 14:28
Show Gist options
  • Save lynxerzhang/2469743 to your computer and use it in GitHub Desktop.
Save lynxerzhang/2469743 to your computer and use it in GitHub Desktop.
read specified bits in byteArray
/**
* study from byteArray.org(about a as3 byteArray's Book)
*/
import flash.utils.ByteArray;
var b:ByteArray = new ByteArray();
b.writeUnsignedInt(1234);
b.writeUnsignedInt(uint.MAX_VALUE);
b.position = 0;
trace(b.readUnsignedInt().toString(2)); //0100, 1101, 0010 (unSignedInt are all 32 bits, use zero for padding)
trace(b.readUnsignedInt().toString(2)); //1111, 1111, 1111 (unSignedInt are all 32 bits, use one for padding)
b.position = 0; //set position to zero
b.readUnsignedByte(); //ignore a byte(8 bits)
b.readUnsignedByte(); //ignore a byte(8 bits)
b.readUnsignedByte(); //ignore a byte(8 bits)
trace(readBits(b, 13).toString(2));
//1101, 0010, 11111 // we get 13 bits in byteArray
/**
* readBits in byteArray
*/
function readBits(b:ByteArray, bitsNum:int):int{
var c:uint = b.readUnsignedByte();
var point:int = 0;
var s:uint = 0;
var result:uint = 0;
for(var i:int = 0; i < bitsNum; i ++){
s = ((1 << (7 - point)) & c) >>> (7 - point);
result |= (s << (bitsNum - 1) - i);
if(++point == 8){
point = 0;
c = b.readUnsignedByte();
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment