gbadev.org forum archive

This is a read-only mirror of the content originally found on forum.gbadev.org (now offline), salvaged from Wayback machine copies. A new forum can be found here.

C/C++ > 16 bit colour question.

#11001 - arthur - Tue Sep 23, 2003 9:55 am

Ok I know that you can use a macro like such:

#define RGB_16BIT(r,g,b) (r+(g<<5)+(b<<10))

to encode a 16 bit value with rgb components. Now how would you go the other way round. i.e. take a 16bit value and return the 3 component values as u8's?

#11005 - torne - Tue Sep 23, 2003 10:09 am

Code:
#define RED(rgb) (rgb & 0xFF)
#define GREEN(rgb) ((rgb >> 5) & 0xFF)
#define BLUE(rgb) ((rgb >> 10) & 0xFF)

#11006 - Burton Radons - Tue Sep 23, 2003 10:43 am

Err, no...

Code:
#define REG_16BIT_RED(rgb) ((rgb) & 31)
#define REG_16BIT_GREEN(rgb) (((rgb) >> 5) & 31)
#define REG_16BIT_BLUE(rgb) (((rgb) >> 10) & 31)
#define RGB_16BIT(r,g,b) ((r)+((g)<<5)+((b)<<10))


There's the problem with the bitwise AND constant, and that one should always surround macro parameter usage with parentheses; if not, then when the expansion has a lower precedence than the arithmetic they're put in, the macro will behave incorrectly. If you're lucky it'll give you a warning (a nigh incomprehensible warning), but more often than not you'll end up staring slack-jawed at code which looks solid but is behaving crazily.

#11007 - torne - Tue Sep 23, 2003 10:50 am

Gah, it's too early in the morning. =)