Fun with Bitwise Operators in C Programming

0 downloads 0 Views 67KB Size Report
Fun with Bitwise Operators in C Programming. The commonly used “bitwise operators” in C are: “~”, “&”, “|”,. “^”,””. These operators have enormous ...
Practitioner Workbench

Amitava Nag Assistant Professor, Head in Dept. of IT, Academy of Technology, West Bengal

Programming.Tips() »

Fun with Bitwise Operators in C Programming The commonly used “bitwise operators” in C are: “~”, “&”, “|”, “^”,””. These operators have enormous power. Bitwise operators work on each bit(1 or 0) of data. Thus bitwise operators make processing faster. The following examples (program to check whether a number is power of 2 or not) show that how bitwise operators reduce computational cost of a program.

printf("\n\t %d is power of 2",n); else printf("\n\t %d not power of 2",n); return 0; } Output:

Function 1: int isPowerOfTwoWB(int n) { int flag=0,c; while(n>1) { c=n%2; if(c==1) { flag=1; break; } n=n/2; } return flag; } If n = 1024, then while loop will be executed 10 (log2(1024)) times. Thus time complexity of isPowerOfTwoWB is O(log2n). On the other hand, the following function (isPowerOfTwoB) written using bit wise “&” (AND) operator gives same result with reduced complexity O(1). int isPowerOfTwoB(int n) { return n&(n-1); }

About the Author

int main() { int n,m; printf("\t Enter a number to check whether it is power of 2: "); scanf("%d",&n); m= isPowerOfTwoB (n); if(m==0)

Enter a number to check whether it is power of 2: 16 16 is power of 2. Enter a number to check whether it is power of 2: 24 24 not power of 2. Another funny C program to obtain binary equivalent of a decimal number using bitwise operator is given below: int main() { int i,n,m,x; printf("\t Enter A Number"); scanf("%d",&n); printf("\ The binary equivalent of %d is ",n); for(i=15;i>=0;i--) { m=1