Search code examples
algorithmcomputer-sciencepascal

Given 8 bits in a byte, how to find all the possible numbers resulting from flipping of one or more bits in this byte


I'm using a byte variable to store color combinations. The value of each bit position represents one color. Thus, by turning one or more bits in the byte on, a combination of colors can be persisted to a memory variable.

I am looking for the algorithm to generate all the possible combinations of [one or more bits of the byte] being in a state of either on or off, with the exception of all bits off ie. 0.

const
  GREEN = 1; //binary 1
  RED = 2; //binary 10;
  BLUE = 4; //binary 100;
  ORANGE = 8; //binary 1000;
  VIOLET = 16; //binary 10000;
  YELLOW = 32; //binary 100000;
  CYAN = 64; //binary 1000000;
  WHITE = 128; //binary 10000000;

This is what the byte looks like with all 8 bits turned on:

The byte


Solution

  • A byte can be thought to represent an unsigned number 0..255. These are represented by the values 0000_0000 and 1111_1111 respectively. Each bit represents a specific power of two. Let's number the bits from left to right with an index, b_i. Then the bits represent a value v_i = 2 ^ b_i when they are on, and zero when they are not on. The number is then the addition of all v_i values.

    Back to your question, the only thing you need to do is to create all byte values except value 0000_0000. You can create a counter that starts with 1 (0000_0001) and then counts to 255. The resulting variable will loop through all possible values. Generally you can, in a programming language, just declare a byte variable to do this (in Pascal: color: byte; it seems), and then use color = color + 1; or color++ if your language supports this. Both the declaration, the addition and the check for <= 255 can be put in a for loop of course.

    A trickier question is how to combine the different colors into a new one? Especially the inclusion of WHITE is vexing. Quite often we simply use Red Green and Blue (RGB), although nowadays professionals work with other color spaces.