Spread the love
Write a Macro’s Set,clear and toggle n’th bit using bit wise operators?
#include<stdio.h> void bin(unsigned n); #define SetBit(number,bit) (number|=(1<<bit-1)) #define ClearBit(number,bit) (number&=(~(1<<bit-1))) #define Toggle(number,bit) (number ^ (1<<bit-1)) int main() { int i=7; printf("\n Binary of 7 is : "); bin(i); i=SetBit(i,4); printf("\n\n Set 4th bit of 7 : "); bin(i); i=ClearBit(i,4); printf("\n\n Clear 4th bit of 7 : "); bin(i); i=Toggle(i,1); printf("\n\n Toggle 1st bit of 7 : "); bin(i); return 0; } void bin(unsigned n) { unsigned i; for (i = (1 << 31) ; i > 0; i = (i>>1)) if(n & i) printf("1"); else printf("0"); }
Output
Suggested Reading
- Count number of 1s in given binary number
- Find position of the only set bit
- Write a c program to implement XOR functionality with out using XOR(^) operator