- 功能:实现对一个8 bit数据(unsigned char类型)的指定位(例如第n位)的置0或者置1操作,并保持其他位不变。
- 函数原型:
void bit_set(unsigned char *date, unsigned char position, int flag)
date
是一个8bit
的unsigned char
类型的数据,position
是指定位,flag
是指定位置0还是置1.- 还有几点是需要注意的,就是指针传参,一定要断言。
- 也要判断输入的值是否有误。
- 函数的具体思路就是先找到指定位,然后把指定位拿出来与flag进行比较,如果一致,则不改动,否则就改变。
- 最后输出从低地址向高地址位输出。
#include<stdio.h>
#include<assert.h>
void bit_set(unsigned char *date, unsigned char position, int flag)
{
assert(date);
if (position > 8 || position < 1 || (flag != 0 && flag != 1))
{
printf("输入有误!\n");
}
if (flag != (*date >> (position - 1)) & 1)
{
*date ^= 1 << (position - 1);
}
for (int i = 7; i >= 0; i--)
{
printf("%d", (*date >> i) & 1);
}
printf("\n");
}
int main()
{
unsigned char date ;
int flag ;
unsigned char position ;
printf("请输入数据和指定位和指定位置0还是1:>");
scanf_s("%d %d %d", &date, &position, &flag);
bit_set(&date, position, flag);
system("pause");
return 0;
}
