【C语言】编写函数,将一个数的指定位置置0或置1

时间:2021-09-09 10:53:10
//编写函数,将一个数的指定位置置0或置1
#include <stdio.h>
unsigned int set_bit(unsigned int num, int pos, int flag)
{
int n = 1;
n = n << (pos - 1); //将n的第pos位置1,其它全为0
if (flag == 0)
{
num = num&(~n);
}
else if (flag == 1)
{
num = num | n;
}
else
printf("flag error\n");
return num;
}
int main()
{
printf("%d\n", set_bit(3,1,0)); //2
printf("%d\n", set_bit(4, 2, 1)); //6
printf("%d\n", set_bit(15, 5, 1)); //31
return 0;
}
<img src="http://img.blog.csdn.net/20150630155139259?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvZG91ZG91d2ExMjM0/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />