To manipulate individual bits there are a number of "bit-wise" operators.
| Operator | Meaning |
|---|---|
| | | Or |
| & | And |
| ^ | Exclusive Or |
| >> | Right Shift |
| << | left Shift |
| ~ | Complement |
|= &= ^= >>= <<=The "|", "&" and "^" operators perform the OR, AND and EXCLUSIVE OR functions between the bits of the two operands. The ">>" and "<<" operators shift the bit patterns to the left or right by the indicated number of places. 1s or 0s that are shifted to the end of a word simply disappear whilst 0s are generated and inserted at the other end. There is no way of rotating a bit pattern in C.
x<<1 is a lazy and obscure way of saying two times "x". The unary operator "~" flips or complements all the bits of its operand. Technically this is a 1's complement not a 2's complement.
For details of bitwise operator precedence see the table at the end of this chapter.
The following program, called int3, enables the user to enter a value and determine the value (1 or 0) of a particular bit.
main()
{
/* Notation used here is that Bit 0 is the
least significant bit
*/
unsigned x;
int n;
printf("Enter a number ");
scanf("%u",&x);
printf("Which bit do you want to see ");
scanf("%d",&n);
printf("It was %u\n",(x>>n)&01);
}
A typical dialogue is shown below $ int3 Enter a number 4 Which bit do you want to see 2 It was 1 $ int3 Enter a number 27 Which bit do you want to see 5 It was 0The expression
(x>>n)&01 is evaluated by first shifting the number x n positions to the right so that the required bit is in the least significant position. The parentheses are necessary because the "&" operator has a higher precedence than the ">>" operator. There is a list of operator precedences at the end of this chapter. After shifting, all the bits other than the least significant are set to zero by ANDing the shifted pattern with the binary bit pattern 0.........0001, here represented by the octal constant 01.
The next example, int4, sets a particular bit to the value 1.
main()
{
unsigned x;
int n;
printf("Enter a number ");
scanf("%u",&x);
printf("Which bit do you want to set ");
scanf("%d",&n);
x |= 01<<n;
printf("After setting bit %d value is %o (Octal)\n",n,x);
printf(" and %d (decimal)\n",x);
}
Again, a typical dialogue $ int4 Enter a number 27 Which bit do you want to set 4 After setting bit 4 value is 33 (Octal) and 27 (decimal) $ int4 Enter a number 27 Which bit do you want to set 5 After setting bit 5 value is 73 (Octal) and 59 (decimal)The expression "01 << n" constructs a bit pattern with the relevant bit set. The assignment operator "|=" performs the setting of the particular bit by ORing 1 with whatever was already in that position. In all other positions in the variable x, 0 is ORed with whatever is already there.
To set a specific bit to 0 rather than 1, the program could be modified to include the following expression
x &= ~(01 << n)