00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014 #pragma once
00015
00019 #include <cassert>
00020
00021 #include "Types.h"
00022
00023 namespace kNet
00024 {
00025
00027 u32 BinaryStringToValue(const char *str);
00028
00030 inline int CountBitsSet(u32 value)
00031 {
00032 int bits = 0;
00033 while(value)
00034 {
00035 value &= value - 1;
00036 ++bits;
00037 }
00038 return bits;
00039 }
00040
00041
00042 inline int ExtractLSB(unsigned long *value)
00043 {
00044 for(int i = 0; i < 32; ++i)
00045 if ((*value & (1 << i)) != 0)
00046 {
00047 *value &= ~(1 << i);
00048 return i;
00049 }
00050 return -1;
00051 }
00052
00061 template<int Bits>
00062 class LSBT
00063 {
00064 public:
00065 enum { val = (1 << Bits) - 1 };
00066 };
00067
00069
00070 template<>
00071 class LSBT<32>
00072 {
00073 public:
00074 enum { val = 0xFFFFFFFF };
00075 };
00076
00077 template<>
00078 class LSBT<31>
00079 {
00080 public:
00081 enum { val = 0x7FFFFFFF };
00082 };
00083
00085
00089 inline u32 LSB(u32 bits)
00090 {
00091 assert(bits <= 32);
00092 if (bits >= 32)
00093 return 0xFFFFFFFF;
00094 return (1 << bits) - 1;
00095 }
00096
00104 template<int Pos, int Bits>
00105 class BitMaskT
00106 {
00107 public:
00108
00109 enum { val = LSBT<Pos+Bits>::val & ~LSBT<Pos>::val };
00110 };
00111
00115 inline u32 BitMask(u32 pos, u32 bits)
00116 {
00117 return LSB(pos + bits) & ~LSB(pos);
00118 }
00119
00122 template<typename ResultType, typename InputType,
00123 int APos, int ABits, int RPos, int RBits,
00124 int GPos, int GBits, int BPos, int BBits>
00125 ResultType PackBits(InputType a, InputType r, InputType g, InputType b)
00126 {
00127 return (ResultType)(
00128 (ResultType)a << APos & BitMaskT<APos, ABits>::val |
00129 (ResultType)r << RPos & BitMaskT<RPos, RBits>::val |
00130 (ResultType)g << GPos & BitMaskT<GPos, GBits>::val |
00131 (ResultType)b << BPos & BitMaskT<BPos, BBits>::val);
00132 }
00133
00135 template<typename ResultType, typename InputType>
00136 ResultType PackBits(int APos, int ABits, int RPos, int RBits,
00137 int GPos, int GBits, int BPos, int BBits,
00138 InputType a, InputType r, InputType g, InputType b)
00139 {
00140 return (ResultType)(
00141 (ResultType)a << APos & BitMask(APos, ABits) |
00142 (ResultType)r << RPos & BitMask(RPos, RBits) |
00143 (ResultType)g << GPos & BitMask(GPos, GBits) |
00144 (ResultType)b << BPos & BitMask(BPos, BBits));
00145 }
00146
00150 template<typename ResultType, typename InputType, int Pos, int Bits>
00151 void ExtractBits(ResultType &out, const InputType &in)
00152 {
00153 out = (ResultType)(in >> Pos & BitMaskT<0, Bits>::val);
00154 }
00155
00159 template<typename ResultType, typename InputType>
00160 void ExtractBits(int pos, int bits, ResultType &out, const InputType &in)
00161 {
00162 out = (ResultType)(in >> pos & BitMask(0, bits));
00163 }
00164
00165 }