# InterviewElements.com

Sunday, Nov 18th

Last update12:59:40 PM GMT

• REGISTER

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

The AND operator

`Truth Table-----------0 AND 0 = 00 AND 1 = 01 AND 0 = 01 AND 1 = 1x AND 0 = 0x 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 = 00 OR 1 = 11 OR 0 = 11 OR 1 = 1x OR 0 = xx OR 1 = 1`
Use bitwise "or" to turn on (set to one) desired bit(s).

The XOR operator
`0 XOR 0 = 00 XOR 1 = 11 XOR 0 = 11 XOR 1 = 0x XOR 0 = xx 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`