码迷,mamicode.com
首页 > 编程语言 > 详细

【c语言】实现对一个8bit数据(unsigned char 类型)的指定位(例如第n位)置0或者置1操作,并保持其他位不变

时间:2015-05-20 09:51:45      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:

// 实现对一个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="" />

【c语言】实现对一个8bit数据(unsigned char 类型)的指定位(例如第n位)置0或者置1操作,并保持其他位不变

标签:

原文地址:http://blog.csdn.net/zhaoyaqian552/article/details/45852845

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!