实现双8bit数据指定的位置0要么1

<pre name="code" class="cpp">
方法一
#include<stdio.h>
#include<math.h>

void bit_set(unsigned char *p_date, unsigned char position, int flag)
{
	char  a =(char) pow(2, (position - 1)); //指数 2^(position - 1)
	if (flag == 1)
	{
		*p_date |= a;//0000 0010或0000 0001   |表示按位或
	}               // 0000 0011
	else 
    {
		*p_date &= ~a; //0000 0010&1111 1110  ~表示按位取反
	}                 // 0000 0010            &表示按位与
	
}

int main()
{
	unsigned char val = 2;
	bit_set(&val, 1, 0);
	printf("%d\n", val);
	getchar();
	return 0;
}



方法二
#include<stdio.h>

void bit_set(unsigned char *p_date, unsigned char position, int flag)
{
	if (flag == 1)
	{
		*p_date |= (1 << (position - 1));//0000 0010或0000 0001
	}                                   // 0000 0011
	else if (flag = 0)
	{
		*p_date &= ~(1 << (position - 1));//0000 0010&1111 1110
	}                                    // 0000 0010
	
}

int main()
{
	unsigned char val = 2;
	bit_set(&val, 1, 0);
	printf("%d\n", val);
	getchar();
	return 0;
}

版权声明:本文博主原创文章,博客,未经同意不得转载。

posted @ 2015-10-19 12:05  mengfanrong  阅读(241)  评论(0)    收藏  举报