【c語言】實現對一個8bit資料(unsigned char 型別)的指定位(例如第n位)置0或者置1操作,並保持其他位不變

zhaoyaqian552發表於2015-05-19
// 實現對一個8bit資料(unsigned char 型別)的指定位(例如第n位)置0或者置1操作,並保持其他位不變

#include <stdio.h>

void bit_set(unsigned char *p_data, unsigned char position, int flag)
{
	unsigned c;
	unsigned char a = 1;
	a = a << (position - 1);
	if (flag == 1)
	{
		*p_data = *p_data | a;
	}
	else
	{
		c = ~a;
		*p_data = *p_data & c;
	}
}

int main()
{
	int pos;
	int flag;
	unsigned char P_data;
	printf("please enter the number:");
	scanf("%d", &P_data);
	printf("please enter the position:");
	scanf("%d", &pos);
	printf("please enter the flag(0 or 1):");
	scanf("%d", &flag);
	bit_set(&P_data, pos, flag);
	printf("the number is %d\n", P_data);
	return 0;
}

<img src="https://img-blog.csdn.net/20150519232954164?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvemhhb3lhcWlhbjU1Mg==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />

相關文章