Next: Some remarks on Up: Data representation Previous: More about types

Bit operations

C allows you to manipulate individual bits within a variable. One way is to use bitwise operations. The following operations (not valid for floats or doubles) are available.

Examples

AND

Bitwise AND to mask off some bits:

   c= n & 0177;

sets to zero all but the lowest 7 bits.

Note the use of an octal constant here. The convention is:

You can make a constant long by appending L eg 0X1234L

OR

The bitwise OR can be used to force bits to be set to 1.

   x= x | 0XFF

forces the lowest 8 bits to 1.

Exclusive OR

Exclusive OR is true if either, but not both, of its two expressions is true. In other words, it produces an output of 1 if and only if precisely one of its two inputs its 1.

The exclusive OR operator is commonly used to change certain bits:

   x= x ^ 03;

means that the lowest pair of bits of x are changed.

Shift

The left-shift is straightforward:

   x << 2

moves the bit pattern x two places to the left, pulling in zeroes in the lowest (rightmost) bit positions. The original top two bits are lost from the left end.

In contrast, the right-shift needs considerable care.

   x >> 2

moves the bit pattern two places to the right. If x is an unsigned quantity, zeroes feed in at the top.

If it is signed, the result depends on the machine: some will fill with zeroes, others with the sign bit.

One's complement

The one's complement operator (~) turns 0's to 1's and vice versa. C also allows you to work directly with bit fields.

Example

Bit fields definitions:

   unsigned flag1 : 1;
   unsigned flag2 : 1;

The fields are defined to be n bits long, with : n. We can now write:

   flag1= 1; flag2= 0;
   if (flag2 == 1)
etc.




Next: Some remarks on Up: Data representation Previous: More about types


maspjw@
Tue Sep 27 15:29:34 BST 1994