Sunday, Nov 18th

Last update12:59:40 PM GMT

What purpose do the bitwise and, or, xor and the shift operators serve?

Write e-mail

The AND operator

Truth Table
0 AND 0 = 0
0 AND 1 = 0
1 AND 0 = 0
1 AND 1 = 1

x AND 0 = 0
x AND 1 = x

We use bitwise "and" to test if certain bit(s) are one or not. And'ing a value against a pattern with ones only in the bit positions you are interested in will give zero if none of them are on, nonzero if one or more is on. We can also use bitwise "and" to turn off (set to zero) any desired bit(s). If you "and" a pattern against a variable, bit positions in the pattern that are ones will leave the target bit unchanged, and bit positions in the pattern that are zeros will set the target bit to zero.



The OR operator

Truth Table
0 OR 0 = 0
0 OR 1 = 1
1 OR 0 = 1
1 OR 1 = 1

x OR 0 = x
x OR 1 = 1

Use bitwise "or" to turn on (set to one) desired bit(s).


The XOR operator

0 XOR 0 = 0
0 XOR 1 = 1
1 XOR 0 = 1
1 XOR 1 = 0

x XOR 0 = x
x XOR 1 = ~x

Use bitwise "exclusive or" to flip or reverse the setting of desired bit(s) (make it a one if it was zero or make it zero if it was one).

The >>, <<, >>=, <<= operators

Operators >> and << can be used to shift the bits of an operand to the right or left a desired number of positions. The number of positions to be shifted can be specified as a constant, in a variable or as an expression. Bits shifted out are lost. For left shifts, bit positions vacated by shifting always filled with zeros. For right shifts, bit positions vacated by shifting filled with zeros for unsigned data type and with copy of the highest (sign) bit for signed data type. The right shift operator can be used to achieve quick multiplication by a power of 2. Similarly the right shift operator can be used to do a quick division by power of 2 (unsigned types only). The operators >> and <<, dont change the operand at all. However, the operators >>= and <=< also change the operand after doing the shift operations.

x << y  - Gives value x shifted left y bits (Bits positions vacated by shift are filled with zeros).
x <<= y - Shifts variable x left y bits (Bits positions vacated by shift are filled with zeros).

A left shift of n bits multiplies by 2 raise to n.

x >> y  - Gives value x shifted right y bits.
x >>= y - Shifts variable x right y bits.

For the right shift, All bits of operand participate in the shift. For unsigned data type,bits positions vacated by shift are filled with zeros. 

For signed data type, bits positions vacated by shift are filled with the original highest bit (sign bit). 

Right shifting n bits divides by 2 raise to n. Shifting signed values may fail because for negative values the result never gets past -1 (minus1):

-5 >> 3 is -1 and not 0 like -5/8

Share this post

Web Hosting