Thursday, 21 February 2013

A program to set nth bit of an integer to 1


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

Explanation:
f |= (1L<<n)
=> f = f | (1L<<n)
in binary; f : 0000 1000
             1L: 0000 0001
   (1L<<2) : 0000 0100  ; bits are shifted to left 2 times.
   | is a bitwise or operator, it will perform or operation and result will be stored to f  so;
                f : 0000 1100
output will be 12.


No comments:

Post a Comment