Bit manipulation

Computer Science AS · Processor fundamentals. The idea in plain words, the rules to remember, the mistake to avoid and a worked example, written and checked by Mega Lecture.

Test this topic freeAll Computer Science AS topics

The idea

A shift moves every bit in a register a number of places left or right. The three kinds differ in what enters the empty places. A logical shift puts in zeros. An arithmetic shift keeps the sign of a two's complement number. A cyclic shift sends each bit that leaves one end back in at the other end.

A mask is a bit pattern used with AND, OR or XOR to test or change chosen bits and leave the others alone. Bits are numbered from the right, starting at bit 0.

This is how devices are monitored and controlled: each bit of a byte can stand for one sensor or one switch.

In simpler words

A shift moves all the bits left or right. A logical shift fills the gaps with 0s. An arithmetic shift keeps the sign of the number. A cyclic shift moves bits off one end and back on the other. A mask is a pattern of bits used with AND, OR or XOR to test or change some bits and leave the rest. Each bit can stand for one switch.

An everyday comparison

A mask works like a stencil over a row of light switches: only the switches under the holes are touched. AND with 0 turns a switch off, OR with 1 turns it on, XOR with 1 flips it. The comparison stops working because a stencil cannot test a switch; an AND mask can, by checking if the result is zero. Shifting also has no stencil match: it moves every bit along at once.

Rules to remember

Common mistake

Students use OR when they want to clear a bit. OR can only set bits to 1; to clear a bit, use AND with a mask that has 0 in that position and 1 everywhere else.

In the exam

State the operation and show the working bit by bit, then give the result. For shifts, say which kind and what fills the empty places, and state that left shift by n multiplies by 2n and right shift divides, losing any remainder. For a mask, choose the operation by the task: AND with 0 to clear or AND to test, OR with 1 to set, XOR with 1 to toggle. Number bits from the right, starting at bit 0.

Worked example

The accumulator holds 01101001. Which operation clears bit 5 (place value 32) to 0 without changing any other bit, and what is the result?

  1. To clear a bit, use AND with a mask that has 0 in that position and 1 in every other position.
  2. Bit 5 is the third bit from the left, so the mask is 11011111.
  3. 01101001 AND 11011111: bit 5 becomes 0 and the other seven bits stay the same, giving 01001001.

Answer: AND B11011111 gives 01001001.

Ask about this

Type what you are stuck on. The helper finds the explanation, worked examples and the notes to read, free and instant.

Keep going

← Assembly languageOperating systems →Take a Computer Science AS test