Saturday, January 23, 2010

11.2.5 THE BITWISE ASSIGNMENT OPERATORS

C also contains the following bitwise assignment operators.
             &=       ^=       |=       <<=         >>=

These operators combine the preceding bitwise operations with ordinary assignments.The left operand must be an assignable integer-type identifier (e.g., an integer variable), and the right operand must be a bitwise expression. The left operand is interpreted as the first operand in the bitwise expression. The value of the bitwise expression is then assigned to the left operand. For example, the expression
a &= 0x7f is equivalent to a = a & 0x7f.

The following program displays the bit pattern corresponding to a signed decimal integer.

#include < stdio.h >


main ()
{
int a, b, m, count, nbits;
unsigned mask;


/*determine the word size in bits and set the initial mask*/
nbits = 8* sizeof (int);
m = 0x1 << (nbits - 1);     /*place 1 in leftmost position*/


/*main loop*/
do {
/*read a signed integer*/
printf("\n\nEnter an integer value (0 to stop): ", a);
scanf("%d", &a);


/*output the bit pattern*/
mask = m;
for (count = 0; count <= nbits; count++)  {
   b = (a & mask) ? 1 : 0;    /*set the display bit on or off*/
   printf("%x", b);               /*print display bit*/

   if (count % 4 == 0)
       printf(" ");      /*blank space after every 4th digit*/
   mask >>= 1;  /*shift mask 1 position to the right*/

}

}


The program is written so that it is independent of the integer word size. Therefore it can be used on any computer.            

No comments:

Post a Comment