00001
00002
00003
00004
00005
00006 namespace NewGamePhysics.Utilities
00007 {
00008 using System;
00009
00013 class BitCount
00014 {
00020 static byte[] bitcountCache;
00021
00025 public BitCount()
00026 {
00027
00028 bitcountCache = new byte[65536];
00029 for (int i = 0; i < 65536; i++)
00030 {
00031 bitcountCache[i] = SparseBitcount(i);
00032 }
00033 }
00034
00040 public int FastBitcount(ushort testThis)
00041 {
00042 return bitcountCache[testThis];
00043 }
00044
00050 public int FastBitcount(short testThis)
00051 {
00052 return FastBitcount((ushort)testThis);
00053 }
00054
00060 public int FastBitcount(uint testThis)
00061 {
00062 return bitcountCache[(testThis >> (0 * 16)) & 65535] +
00063 bitcountCache[(testThis >> (1 * 16)) & 65535];
00064 }
00065
00071 public int FastBitcount(int testThis)
00072 {
00073 return FastBitcount((uint)testThis);
00074 }
00075
00081 public int FastBitcount(ulong testThis)
00082 {
00083 return bitcountCache[(testThis >> (0 * 16)) & 65535L] +
00084 bitcountCache[(testThis >> (1 * 16)) & 65535L] +
00085 bitcountCache[(testThis >> (2 * 16)) & 65535L] +
00086 bitcountCache[(testThis >> (3 * 16)) & 65535L];
00087 }
00088
00094 public int FastBitcount(long testThis)
00095 {
00096 return FastBitcount((ulong)testThis);
00097 }
00098
00104 public int FastBitcount(double testThis)
00105 {
00106
00107 long testThisBits = BitConverter.DoubleToInt64Bits(testThis);
00108 return FastBitcount((ulong)testThisBits);
00109 }
00110
00118 static private byte SparseBitcount(int testThis)
00119 {
00120 int count = 0;
00121 while (testThis != 0)
00122 {
00123 count++;
00124 testThis &= (testThis - 1);
00125 }
00126
00127 return (byte)count;
00128 }
00129 }
00130 }