#include <stdio.h>
#include <windows.h>
#include <math.h>
//#pragma warning (disable:4996)
/*
功能:实现一个8 bit位数据的指定位置1或0
*/
/*方法1*/
void bit_set(unsigned char *p_data, unsigned char position, int flag)
{
char a = (char)pow(2, (position - 1));//2 的(position - 1)次方
if (flag == 1)
*p_data |= a;//2的第一位置1:0000 0010 | 0000 0001 == 0000 0011
else if (flag == 0)
*p_data &= ~a;//2的第二位置0:0000 0010 & (~0000 0010) == 0000 0000
}
/*方法2*/
void bit_set_two(unsigned char *p_data, unsigned char position, int flag)
{
if (flag == 1)
*p_data |= (1 << (position - 1));
else if (flag == 0)
*p_data &= ~(1 << (position - 1));
}
int main()
{
unsigned char num = 2;
bit_set(&num, 1, 1);
printf("First: num = %d\n", num);
bit_set_two(&num, 2, 0);
printf("Second: num = %d\n", num);
system("pause");
return 0;
}
实现一个8 bit位数据的指定位置1或0
最新推荐文章于 2023-06-25 15:39:54 发布