Friday, November 4, 2011

Bitwise Operators in C programming

Bitwise Operators

One of C’s powerful features is a set of bit manipulation operators. These permit the programmer to access and manipulate individual bits within a piece of data. The various Bitwise Operators available in C are shown in Figure


These operators can operate upon ints and chars but not on floats and doubles. Before moving on to the details of the operators, let us first take a look at the bit numbering scheme in integers and characters. Bits are numbered from zero onwards, increasing from right to left as shown below:





Throughout this discussion of bitwise operators we are going to use a function called showbits( ), but we are not going to show you the details of the function immediately. The task of showbits( ) is to display the binary representation of any integer or character value.
We begin with a plain-jane example with showbits( ) in action.
 
/* Print binary equivalent of integers using showbits( ) function */
main( )
{
int j ;
for ( j = 0 ; j <<= 5 ; j++ )
{
printf ( "\nDecimal %d is same as binary ", j ) ;
showbits ( j ) ;
}
}

And here is the output...
Decimal 0 is same as binary 0000000000000000
Decimal 1 is same as binary 0000000000000001
Decimal 2 is same as binary 0000000000000010
Decimal 3 is same as binary 0000000000000011
Decimal 4 is same as binary 0000000000000100
Decimal 5 is same as binary 0000000000000101
Let us now explore the various bitwise operators one by one.

No comments:

Post a Comment