C语言一些常用的“位”操作函数

这些函数操作“位”,经常用到:

//将双字节中某一位置位
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,语言)