Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate 24-bit RGB values "more gracefully"?

Tags:

c

algorithm

rgb

Source file:

/* gcc <filename.c> -o <filename> -std=c99 -Wall */
   
#include <stdio.h>

int main (void)
{
  unsigned int RGB[8];
  for (unsigned char Cnt = 1; Cnt < 8; Cnt++)
  {
    RGB[Cnt] =   ((unsigned int)((6+Cnt)/7)) * (((unsigned int) 0xFF) << (8*((9-Cnt)%3)))
               + ((unsigned int) (Cnt/4))    * (((unsigned int) 0xFF) << (8*((8-Cnt)%3)))
               + ((unsigned int) (Cnt/7))    *  ((unsigned int) 0xFF);
    fprintf (stdout, "%06X\n", RGB[Cnt]);
  }
}

Output: (order: R -> G -> B -> R+G -> G+B -> B+R -> R+G+B)

FF0000

00FF00

0000FF

FFFF00

00FFFF

FF00FF

FFFFFF

I wonder...

  • whether there are any more graceful ways to generate 24-bit RGB values in this order as above?

  • whether those type-castings are necessary in ISO C99?

  • whether unsigned symbols in type-casting are necessary in ISO C99 in this case?

Thanks.

like image 883
Kevin Dong Avatar asked Dec 04 '25 14:12

Kevin Dong


2 Answers

Simple way is just to hardcode values, it will be easy to read.

Anyway if you want to generate them - this variant is faster neither integer division:

unsigned int RGB[7];
unsigned int values[] = {0, 0xff};
unsigned int rgbmask = 0x1EBC54; // binary 111101011110001010100
for (int i=0; i<7; i++)
{
    RGB[i] = values[rgbmask>>2&1]<<16 | values[rgbmask>>1&1]<<8 | values[rgbmask&1];
    rgbmask >>= 3;
    printf ("%06X\n", RGB[i]);
}
like image 137
Iłya Bursov Avatar answered Dec 07 '25 04:12

Iłya Bursov


Possibly not what you wanted to see, but this seems so much better:

unsigned int RGB[8] = {
    0x000000,
    0xFF0000,
    0x00FF00,
    0x0000FF,
    0xFFFF00,
    0x00FFFF,
    0xFF00FF,
    0xFFFFFF
};
like image 26
M.M Avatar answered Dec 07 '25 06:12

M.M



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!