Thursday 21 February 2013

a program to set nth bit of an integer to 0


#include<stdio.h>
#include<conio.h>
void main()
{
int n=2;
int f=12;
clrscr();
f&=~(1L<<n);
printf("%d",f);
getch();
}


Explanation:
f &=~(1L<<n)
=> f = f & ~ (1L<<n)
in binary; f : 0000 1100
             1L: 0000 0001
   (1L<<2) : 0000 0100  ; bits are shifted to left 2 times.
  ~(1L<<2) : 1111 1011 ; complement the bits.
  &  is a bitwise AND operator, it will perform AND operation and result will be stored to f  so;
                f : 0000 1000
output will be 8.



No comments:

Post a Comment