How to Do Run-Length Encoding on a Bitmap Row
Learn how to run-length encode a bitmap row by counting consecutive pixels of the same colour, recording count-colour pairs, and avoiding GCSE mistakes.
To do run-length encoding (RLE) on a bitmap row, read the pixels from left to right. Count how many consecutive pixels have the same colour, then record that count and the colour. Start a new count whenever the colour changes.
A bitmap stores an image as pixels. A run is a group of neighbouring pixels with the same value or colour. RLE stores each run instead of listing every pixel separately.
To keep track, start with the first pixel and set its run count to 111. Compare each following pixel with the one before it. If the colours match, increase the count by 111. If the colour changes, record the completed run and start a new run with a count of 111. When you reach the end of the row, record the final run too. Otherwise, your encoded row will be incomplete.
Worked example
Suppose a row contains white, white, white, black, black, white, white. Let W\mathrm{W}W mean white and B\mathrm{B}B mean black. The row is:
W,W,W,B,B,W,W \mathrm{W},\mathrm{W},\mathrm{W},\mathrm{B},\mathrm{B},\mathrm{W},\mathrm{W} W,W,W,B,B,W,WReading from the left, there are 333 white pixels, then 222 black pixels, then 222 white pixels. Using count, colour pairs, the encoded row is:
(3,W),(2,B),(2,W) (3,\mathrm{W}),(2,\mathrm{B}),(2,\mathrm{W}) (3,W),(2,B),(2,W)You can check your answer by decoding it: write 333 white pixels, 222 black pixels and 222 white pixels. You should get the original row back.
Watch out
Do not combine the white pixels at the beginning and end into one run. They are separated by black pixels, so they must be recorded separately. Also check the format given in the question: some questions specify a starting colour and ask for run lengths only, while others require both the count and the colour. If you are encoding more than one row, finish one row before starting the next.
RLE works best when there are long runs of identical pixels. A row whose colour changes after almost every pixel may not become shorter.