Manipulating Bits

Bitwise operators and how to use bit masks. The applications included demonstrate calculations with parity bits, conversion of lowercase and capital letters, and converting binary numbers. Finally, the definition of bit-fields is introduced.

Bitwise Operators

"True or False" table for bitwise operators


Bit Coding Data

In cases where conservative use of memory is imperative, data often need to be bit coded, a technique to represent information as individual bits. Some examples of bit coded data can be found in file access rights or the status-word of a stream.
To access bit coded data, you need to be able to read or modify individual bits. C++ has six bitwise operators to perform these tasks:
  • Logical bitwise operators
    &    AND |            inclusive OR
    ^   exclusive OR ~             NOT
  • Bitwise shift operators
    << Left shift >> Right shift
Operands for bitwise operators must have integral types. Operands belonging to float or double types are invalid.
The boolean tables on the opposite page show the effect of the logical bitwise operators for individual bits. If a bit is set, that is, if it has a value of 1, it will be interpreted as true. If the bit is not set, and thus has a value of 0, it will be interpreted as false. Examples for each bitwise operator follow.
The result type of a bitwise operation will be the integral type defined by the operand type. If, for example, both operands are int types, the result will also be of an int type.

Arithmetic Type Conversions and Precedence

If the operands of a bitwise operator are of different types, normal arithmetic type conversion will occur. If one operand type is an int and the other a long, the int value will be converted to long before the operation is performed.
The logical bitwise operators & or | should not be confused with the logical && and || operators. The latter do not affect individual bits but interpret the whole value of their operands as boolean, returning a boolean value. The expression 1 && 2 returns the value true, whereas 1 & 2 has the value 0.
The precedence of the bitwise NOT operator ~ is high, since ~ is a unary operator. As you can see from the table of precedence in the appendix, both the binary operators &, ^, and | have low precedence. However, their precedence is higher than that of the logical operators && and ||.

 

Post a Comment

0 Comments