这些函数操作“位”,经常用到:
//将双字节中某一位置位
void SetN1(unsigned short *pBuf, int n)
{
(*pBuf) |= 1<<n;
}
//将双字节中某一位清零
void SetN0(unsigned short *pBuf, int n)
{
(*pBuf) &= ~(1<<n);
}
//将单字节中某一位置位
void SetN1(unsigned char *pBuf, int n)
{
(*pBuf) |= 1<<n;
}
//将单字节中某一位清零
void SetN0(unsigned char *pBuf, int n)
{
(*pBuf) &= ~(1<<n);
}
//获得单字节中某一位的值
int Get1Bit(unsigned char buf, int n)
{
return (buf>>n) & 0x01;
}
//获得双字节中某一位的值
int Get1Bit(unsigned short buf, int n)
{
return (buf>>n) & 0x01;
}
//获得单字节中两位的值
int Get2Bit(unsigned char buf, int n)//n必须是2的倍数
{
return (buf>>n) & 0x03;
}
//获得双字节中两位位置(n)处的值
int Get2Bit(unsigned short buf, int n)//n必须是2的倍数
{
return (buf>>n) & 0x03;
}
//将单字节中两位位置(n)处,设置数值(m)
void Set2Bit(unsigned short *pBuf, int n, int m)//n必须是2的倍数
{
(*pBuf) |= m<<n;
}
其实,最方便操纵“位”,如果不限制C语言的话,使用C++的STL中bitset最方便。
本文详细介绍了几种常用的位操作函数,包括设置位、清除位及获取位的值等,并提供了具体的C语言实现示例。此外还提到了使用C++ STL中的bitset进行位操作的优势。
1154

被折叠的 条评论
为什么被折叠?



