// 实现对一个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="http://img.blog.csdn.net/20150519232954164?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvemhhb3lhcWlhbjU1Mg==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />
时间: 2024-12-26 20:49:48