清楚变量的某位
位的清除在嵌入式领域至关重要,配置寄存器的某些位相当方便
C++语言实现
#include <iostream>
#define BIT_MASK(bit_pos) ( 0x1 <<( bit_pos ) )
int Bit_Clear(unsigned int *val,unsigned char pos);
int main(void)
{
unsigned int x= 0xffffffff;
unsigned char y = 4;
Bit_Clear(&x,y);
std::cout<<std::hex<<x<<'\n';
return 0;
}
int Bit_Clear(unsigned int *val,unsigned char pos)
{
// error pos > biggest_bits_index
if( pos >= sizeof( unsigned int ) * 8 )
return 0;
*val = ( *val & ~BIT_MASK ( pos ) );
return 1;
}
结果是:
ffff_ffef
值得注意的是:
寄存器的位序号是从 0 开始计数的。从右到左 : 0 、1 、 2 、 3 、 4 …… 屏蔽序号 pos = 4 是 意味着 屏蔽第五位 。