eg:10: 0000 1010
让其bit为的第3个位置1操作,就变成0000 1110 对应的数据是14
观察
0000 1010
0000 1110
其它位不变,指定位从0变为1,可以想到给指定位或1后该位为1,其它位或0而保持不变。
0000 1010
0000 0100(将1左移指定位减一位)
按位或
0000 1110
同理
让其bit为的第4个位置0操作,就变成0000 0010 对应的数据是2
观察
0000 1010
0000 1110
其它位不变,指定位从1变为0,可以想到给指定位与0后该位为0,其它位与1而保持不变。
0000 1010
1111 0111(将1左移指定位减一位然后按位取反)
按位或与
0000 0010
#include <stdio.h>
#include <Windows.h>
#include <assert.h>
void bit_set(unsigned char* p_data, unsigned char position, int flag)
{
assert(p_data);
assert((position >= 1) && (position <= 8));
if (flag == 0)
{
*p_data &= ~(1 << (position-1));
}
else
{
*p_data |= (1 << (position-1));
}
}
int main()
{
unsigned char data = 4;//0100
bit_set(&data, 2, 1);//0110
printf("%d\n",data);
system("pause");
return 0;
}