常用的位操作:置位、清零与测试

版权声明:本文为博主原创文章,转载请注明来自http://blog.csdn.net/jediael_lu/ https://blog.csdn.net/jediael_lu/article/details/8577768

以下程序可用于把某个位置位、清零或测试某位为0还是1:

#include <stdio.h>
#include <stdbool.h>

int setbit(int num, int bit);
int clearbit(int num, int bit);
bool testbit(int num, int bit);

int main(void){
	int num=0x8A26;
	int new_num;

	new_num=setbit(num, 3);
	printf("num=%d\tnew_num=%d.\n", num, new_num);

	new_num=clearbit(num, 2);
	printf("num=%d\tnew_num=%d.\n", num, new_num);

	printf("%d\n",testbit(num, 2));

	return 0;
}

int setbit(int num, int bit){
	return num|=(1<<bit);
}

int clearbit(int num, int bit){
	return num&=~(1<<bit);
}

bool testbit(int num, int bit){
	return num&=(1<<bit);
}


阅读更多
换一批

没有更多推荐了,返回首页