/*以下模板函数中的a、b变量值的含义
bit location define:
0~31
31 ... 24 23 ... 16 15 ... 8 7 ... 0
0~63
63 ... 32 31 ... 24 23 ... 16 15 ... 8 7 ... 0
*/
//get bits a-->b from f
template<typename T>
T GetBits(T f, UINT32 a, UINT32 b)
{
ASSERT((a >= 0) && (b < (sizeof(T)<<3)) && (a <= b));
return T((((UINT64)f)&(((1<<(b-a+1))-1)<<a))>>a);
}
//get one bit from f
template<typename T>
T GetBit(T f, UINT32 a)
{
ASSERT((a >= 0) && (a < (sizeof(T)<<3)));
return T((((UINT64)f)&((UINT64)1<<a))>>a);
}
//set bits a-->b from f to t
template<typename T>
void SetBits(T &t, T f, UINT32 a, UINT32 b)
{
ASSERT((a >= 0) && (b < (sizeof(T)<<3)) && (a <= b)
&& (f < (T)(1<<(b-a+1))));
t=T(((((UINT64)(f))&((1<<(b-a+1))-1))<<a)
|((UINT64)(t)&(~(((1<<(b-a+1))-1)<<a))));
}
//set one bit from f to t
template<typename T>
void SetBit(T &t, T f, UINT32 a)
{
ASSERT((a >= 0) && (a < (sizeof(T)<<3)) && ((f==0)||(f==1)));
t=((f==1)? (T((UINT64)(t))|(1<<a)):(T((UINT64)(t))&(~(1<<a))));
}
cpp位操作模板函数
最新推荐文章于 2024-04-12 03:40:07 发布