Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cycle through all rgb values [duplicate]

rgb range of 0-255 for each (red, green and blue) means that there should be 256x256x256 possible rgb colour values.

How can I loop through and print every single value?

I don't need a specific order yet I just want to know how to go through and get all values without skipping any.

like image 508
user3387566 Avatar asked Mar 04 '26 09:03

user3387566


1 Answers

You can simply use 3 nested loops:

var red, green, blue;

for (red = 0; red <= 255; red++) {
    for (green = 0; green <= 255; green++) {
        for (blue = 0; blue <= 255; blue++) {
            // rgb(red, green, blue)
        }
    }
}

Order:

 R  |  G  |  B
---------------
  0 |   0 |   0
  0 |   0 |   1
  0 |   0 |   2
...............
255 | 255 | 253
255 | 255 | 254
255 | 255 | 255

An alternative is a loop that loops to 256 * 256 * 256 (16777216):

var red, green, blue;

for (var rgb = 0; rgb <= 16777216; rgb++) {
    red   = (rgb >> 16) & 0xFF;
    green = (rgb >> 8) & 0xFF;
    blue  = (rgb) & 0xFF;

    // rgb(red, green, blue)
}

Here the order would be:

 R  |  G  |  B
---------------
  0 |   0 |   0
  1 |   0 |   0
  2 |   0 |   0
...............
253 | 255 | 255
254 | 255 | 255
255 | 255 | 255

The performance won't be as good though, as you'd use a lot of logic.

like image 100
h2ooooooo Avatar answered Mar 05 '26 21:03

h2ooooooo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!