Packing Bits
Quick and dirty example of bit packing. This example treats each byte, of a 32-bit INT, as a unique value. This example ignores the last byte, the source of the code only needed to store 3 bytes worth of data.
The main bit packer:
public class BitPack { public BitPack(){ _data = 0; } private System.Int32 _data; public System.Int32 Data { get { return _data;} set { _data = value; } } /// <summary> /// low 8 bits [1-8] /// </summary> public System.Int32 Low { get { return (_data & 0xFF); } set { _data &= 0xFFFF00; //clear _data |= value; } } /// <summary> /// mid 8 bits [9-16] /// </summary> public System.Int32 Mid { get { return (_data >> 8 & 0xFF); } set { _data &= 0xFF00FF; //clear _data |= value<<8; } } /// <summary> /// high 8 bits [17-24] /// </summary> public System.Int32 High { get { return (_data >> 16 & 0xFF); } set { _data &= 0x00FFFF; //clear _data |= value<<16; } } }
Example wrapper, a coordinate pack:
public class PosPack : BitPack { public PosPack(){} public PosPack(PosPack p){ X = p.X; Y = p.Y; } public PosPack(System.Int32 x, System.Int32 y){ X = x; Y = y; } /// <summary> /// x coordinate /// </summary> public System.Int32 X { get{return Low * XSign;} set { Low = System.Math.Abs(value); if(value < 0)XSign = 0; else XSign = 1; } } /// <summary> /// y coordinate /// </summary> public System.Int32 Y { get{return Mid * YSign;} set { Mid = System.Math.Abs(value); if(value < 0)YSign = 0; else YSign = 1; } } /// <summary> /// x sign /// </summary> private System.Int32 XSign{ get{ if ((High & 0xF) > 0) return 1; return -1; } set{ //High stores 2 values, only overwrite lower 4 bits int tmp = High; tmp &= 0xF0; tmp |= value; High = tmp; } } /// <summary> /// y sign /// </summary> private System.Int32 YSign{ get{ if ((High >> 4 & 0xF) > 0) return 1; return -1; } set{ //High stores 2 values, only overwrite upper 4 bits int tmp = High; tmp &= 0x0F; tmp |= (value << 4); High = tmp ; } } }
And Usage
PosPack p = new PosPack(-12,13); Console.Write("X Should be -12: " + p.X); Console.Write("Y Should be 13: " + p.Y);
Bits [1-8] store the x coordinate, bits [9-16] store the y coordinate, and bits [17-24] store the sign. You might ask yourself why use 8 bits to store the sign? You wouldn’t, not in an efficient example. I discretized my example along 4 bit chunks to make it easier to understand. In reality I would only need 18 bits.
You might also ask why would anyone go to this much effort to store 2 ints? The answer is two-fold: Networking and hashing. We can now transmit just 1 integer that can be split in to 8 bit increments for serialization. If you’re using C# you can let the compiler handle serialization for you.






.