Matthew Hipkin

Cycle Every Possible RGB Colour

Ever wanted to spit out every single RGB colour combination? Nope, niether have I. It's still a fun little programming challenge, and allows you to get more familiar with bitwise operations.

There are 16,777,216 possible colours (256 * 256 * 256) and we can extract the red, green and blue bits from each value as we iterate from 0 to 16,777,216 - this is the same as manually calculating the red, green and blue values on each loop iteration albeit much faster.

program cyclergb;
{$mode objfpc}{$H+}
uses Classes, SysUtils;

procedure main;
const
  TAB = #9;
var
  i, r, g, b, maxcol: Integer;
  F: TextFile;
begin
  maxcol := 256 * 256 * 256;
  AssignFile(F,'rgb.txt');
  Rewrite(F);
  for i := 0 to maxcol-1 do
  begin
    r := (i shr 16) and $FF;
    g := (i shr 8) and $FF;
    b := i and $FF;
    writeln(F,r,TAB,g,TAB,b);
  end;
  CloseFile(F);
end;

begin
  main;
end.

Upon completion this program would have produced a TSV file that is around 180mb in size (available here bzipped ~22mb) which you may find some use for.

Posted in rgb on 2019-05-21 21:41:06

blog comments powered by Disqus