Go Down

Topic: runtime convert HEX colorcode to RGB565 colorcode (Read 830 times) previous topic - next topic



25 years ago I coded a lot of Basic, Turbo Pascal and Visual Basic.
But I never coded one line arduino up til now.
This is why I need some help to get started with it.

I'm looking for a small function that converts a HEX colorcode to a RGB565 colorcode during runtime.

Some easy examples:
#000000 should return 0x0000 (black)
#FF0000 should return 0xF800 (red)
#00FF00 should return 0x07E0 (green)
#0000FF should return 0x001F (blue)
#FFFFFF should return 0xFFFF (white)

...and so on.

The best code I found up til now is:

Code: [Select]

uint16_t rgb565( const unsigned long rgb)
  uint16_t R = (rgb >> 16) & 0xFF;
  uint16_t G = (rgb >>  8) & 0xFF;
  uint16_t B = (rgb      ) & 0xFF;

  uint16_t ret  = (R & 0xF8) << 8;  // 5 bits
           ret |= (G & 0xFC) << 3;  // 6 bits
           ret |= (B & 0xF8) >> 3;  // 5 bits
  return( ret);

This is nice short and easy.
But it works not exactly like I need it.
Maybe somebody can adapt this for me, that it returns "0x07E0" when it gets "#00FF00" ?

Thanks and best regards,


Maybe somebody can adapt this for me, that it returns "0x07E0" when it gets "#00FF00" ?
It does return 0x7E0... are you actually trying to convert strings to and from hex?
Please ask questions in the forum so everyone can benefit. PM me for paid work.


Hi Bob,

thanks for your answer.
I think you get it right.
It looks that I found the answer in the german forum.

Thanks and best regards,

Go Up