Friday 2 December 2011

The Bitfield class

This is a simple class I made to handle bitfields in ActionScript. It's main purpose is to make it easy to save flags for preference and progress as integers, alongside other integers so simplifying the code for loading and saving which was tricky to debug.


It includes methods to access individual bits and the whole data as an integer for saving. I also added a function to sum the number of bits, to count the number of awards as they were stored in a Bitfield.



class Bitfield {

 var iData:uint;
 static const iIndexMax:int = 29; // 30 bits
 
 function Bitfield(iInit:uint = 0):void {
  iData = iInit;
 }
 
 function Clear():void {
  iData = 0;
 }
 
 function Data():uint {
  return iData;
 }
 
 function SetBit(iIndex:int, bState:Boolean):void {
  var iMask1:uint = 1 << iIndex;
  var iMask2:uint = ~iMask1;
  
  iData &= iMask2;
  if (bState) {
   iData |= iMask1;
  }
 }
 
 function GetBit(iIndex:int):Boolean {
  var iMask1:uint = 1 << iIndex;
  return (iData & iMask1) > 0;
 }
 
 function NumBits():int {
  var iNum:int = 0, iCopy:uint = iData, iMask:uint = 0x01;
  
  while (iCopy > 0) {
   iNum += iCopy & iMask;
   iCopy >>= 1;
  }
  
  return iNum;
 }
}

No comments:

Post a Comment