16位色和24位色转换宏

 



#include <assert.h>
typedef unsigned long DWORD;
typedef unsigned char BYTE;
typedef unsigned short WORD;

// 24位色和16位色转换宏
// by cheungmine
#define RGB888toRGB565(r,g,b) ((WORD)(((WORD(r)<<8)&0xF800)|((WORD(g)<<3)&0x7E0)|((WORD(b) >> 3))))

#define RGBtoRGB565(rgb) ((WORD)(((((WORD)((rgb)>>3))&(0x1F))<<11)|((((WORD)((rgb)>>10))&(0x3F))<<5)|(((WORD)((rgb)>>19))&(0x1F))))

#define RGB888toRGB555(r,g,b) ((WORD)(((WORD(r)<<7)&0x7C00)|((WORD(g)<<2)&0x3E0)|((WORD(b)>>3))))

#define RGBtoRGB555(rgb) ((WORD)(((((WORD)((rgb)>>3))&(0x1F))<<10)|((((WORD)((rgb)>>11))&(0x1F))<<5)|(((WORD)((rgb)>>19))&(0x1F))))

#define RGB555toRGB(rgb555) ((DWORD)(((BYTE)(((rgb555)>>7)&0xF8)|((WORD)((BYTE)(((rgb555)>>2)&0xF8))<<8))|(((DWORD)(BYTE)(((rgb555)<<3)&0xF8))<<16)))

#define RGB565toRGB(rgb565) ((DWORD)(((BYTE)((((rgb565)&0xF800)>>11)<<3)|((WORD)((BYTE)((((rgb565)&0x07E0)>>5)<<2))<<8))|(((DWORD)(BYTE)(((rgb565)&0x001F)<<3))<<16)))


int main(int argc, char* argv[])
{
COLORREF rgb = RGB(193,192,191);

WORD w = RGB888toRGB565(193, 192, 191);
WORD w2 = RGBtoRGB565(rgb);
assert(w==w2);

COLORREF rgb1 = RGB565toRGB(w);

WORD w5 = RGBtoRGB565(rgb1);
assert(w5==w2);

WORD w3 = RGB888toRGB555(193, 192, 191);
WORD w4 = RGBtoRGB555(rgb);
assert(w3==w4);

COLORREF clr = RGB555toRGB(w4);
w4 = RGBtoRGB555(clr);

return 0;
}