Skip to content
Questions
Definition
Bitwise manipulation means working directly on the individual bits of a binary value, by shifting them or by combining the value with a mask.

Shifts

Definition
A logical shift moves every bit of a binary number left or right by a given number of places. Bits pushed off the end are lost and the empty places are filled with 0s.
Key Point
ShiftEffect on the valueExample (8 bits)
Left by 1 placeMultiplies by 200010110 (22) → 00101100 (44)
Left by 2 placesMultiplies by 400010110 (22) → 01011000 (88)
Right by 1 placeDivides by 200010110 (22) → 00001011 (11)
Right by 3 placesDivides by 801011000 (88) → 00001011 (11)

Shifting left by n places multiplies the number by 2^n, and shifting right by n places divides it by 2^n. A shift is much quicker for the processor than a full multiplication or division.

Warning
When a shift gives the wrong answer:
• A 1 shifted off the left-hand end is lost (overflow): 11000000 (192) shifted left 1 place gives 10000000 (128), not 384
• A 1 shifted off the right-hand end is lost, so the result is rounded down: 00001011 (11) shifted right 1 place gives 00000101 (5), not 5.5

Masks

Definition
A mask is a binary pattern that is combined with a value using AND, OR or XOR, so that chosen bits are tested, cleared, set or flipped while the others are left alone.
Key Point
OperationWhere the mask has a 1Where the mask has a 0Used to
ANDThe bit is keptThe bit becomes 0Clear bits, or pick out (extract) bits
ORThe bit becomes 1The bit is keptSet bits to 1
XORThe bit is flippedThe bit is keptFlip (toggle) bits
Worked Example
Worked Example: Applying a Mask

Apply the mask 00001111 to the value 10110110.
RowANDORXOR
Value101101101011011010110110
Mask000011110000111100001111
Result000001101011111110111001
• AND kept the right-hand four bits and cleared the rest
• OR set the right-hand four bits to 1
• XOR flipped the right-hand four bits
Example
Using masks:
• To test whether a number is odd, AND it with 00000001. A result of 1 means the last bit was set
• In ASCII, 'A' is 01000001 and 'a' is 01100001. OR with 00100000 turns a capital letter into lower case, and AND with 11011111 turns it back
• XOR with 11111111 flips every bit, which is the same as NOT
Exam Tip
Choosing the operation:
• Keep some bits and clear the rest: AND
• Force bits to 1: OR
• Flip bits: XOR
• Write the mask with the same number of bits as the value and work down each column