The Bitwise Operators

C and C++ provide operators that act upon the actual bits that comprise a value. The bitwise operators can be used only on integral types. The bitwise operators are as follows:

Operator

Meaning

&

AND

|

OR

^

XOR

~

One’s complement

>>

Right shift

<<

Left shift

&, |, and ^

The truth tables for &, |, and ^ are as follows:

p

q

p & q

p | q

p ^ q

0

0

0

0

0

0

1

0

1

1

1

1

1

1

0

1

0

0

1

1

These rules are applied to each bit in each operand when the bitwise AND, OR, and XOR operations are performed.

For example, a sample bitwise AND operation is shown here:

 

0 1 0 0   1 1 0 1

      &

0 0 1 1   1 0 1 1

 

0 0 0 0   1 0 0 1

A bitwise OR operation looks like this:

 

0 1 0 0   1 1 0 1

     |

0 0 1 1   1 0 1 1

 

0 1 1 1   1 1 1 1

A bitwise XOR operation is shown here:

 

0 1 0 0   1 1 0 1

      ^

0 0 1 1   1 0 1 1

 

0 1 1 1   0 1 1 0

The One’s Complement Operator

The one’s complement operator, ~, will invert all the bits in its operand. For example, if a character variable, ch, has the bit pattern

0 0 1 1   1 0 0 1

then

ch = ~ch;

places the bit pattern

1 1 0 0   0 1 1 0

into ch.

The Shift Operators

The right (>>) and left (<<) shift operators shift all bits in an integral value by the specified amount. As bits are shifted off one end, zeros are brought in the other end. (If the value being shifted is a negative, signed number and a right shift is performed, then ones are shifted in to preserve the sign.) The number on the right side of the shift operator specifies the number of positions to shift. The general form of each shift operator is

 value >> number  value << number 

Here, number specifies the number of positions to shift value.

Given this bit pattern (and assuming an unsigned value),

0 0 1 1   1 1 0 1

a shift right yields

0 0 0 1   1 1 1 0

while a shift left produces

0 1 1 1   1 0 1 0 
Programming Tip 

A shift right is effectively a division by 2, and a shift left is a multiplication by 2. For many computers, a shift is faster than a multiply or a divide. Therefore, if you need a fast way to multiply or divide by 2, consider using the shift operators. For example, the following code fragment will first multiply and then divide the value in x by 2:

int x; x = 10; x = x << 1; x = x >> 1; 

Of course, when using the shift operators to perform multiplication, you must be careful not to shift bits off the end.

The precedence of the bitwise operators is shown here:

Precedence

Operators

Highest

~

 

>>   <<

 

&

 

^

Lowest

|




C(s)C++ Programmer's Reference
C Programming on the IBM PC (C Programmers Reference Guide Series)
ISBN: 0673462897
EAN: 2147483647
Year: 2002
Pages: 539

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net