功能:实现对一个8 bit数据(unsignedchar类型)的指定位(例如第n位)的置0或者置1操作,并保持其他位不变。
函数原型:
void bit_set(unsigned char *p_data, unsignedchar position, int flag)
函数参数说明:
P_data是指定的源数据,position是指定位(取值范围1~8);flag表示是置0还是置1操作
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
void bit_set(unsigned char *p_data, unsigned char position, int flag)
{
int i = 0;
assert(p_data);
if (position > 8 || position < 1 || (flag != 0 && flag != 1))
{
printf("输入有误!\n");
return;
}
if (flag != (*p_data >> (position - 1) & 1))
{
*p_data ^= 1 << (position - 1);
}
for (i = 7; i >= 0; i--) //由低地址的位开始输出。
{
printf("%d", (*p_data >> i) & 1);
}
printf("\n");
}
int main()
{
unsigned char data = 3;
int flag = 0;
unsigned char position = 2;
bit_set(&data, position, flag); //这里测试的是把数字3的第二位置0.
system("pause");
return 0;
}
输出结果; 3本来应该是00000011,将第二位置0后应该是00000001.