以下程序可用于把某个位置位、清零或测试某位为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);
}