我找到了三种 RGB888 到 RGB565 的转换算法,但我不确定哪种最正确。前两种产生相同的结果。第三种产生不同的结果,但与在线计算器一致。第三种是有道理的,因为它可以缩放。但前两种会更快,因为没有整数乘法或除法。
uint8_t r8, g8, b8;
uint16_t r5, g6, b5, val;
r8 = someredvalue;
g8 = somegreenvalue;
b8 = somebluevalue;
// first method:
b5 = (b8 >> 3) & 0x001F;
g6 = ((g8 >> 2) << 5) & 0x07E0;
r5 = ((r8 >> 3) << 11) & 0xF800;
val = (r5 | g6 | b5);
printf("%d, %d, %d, %u\n", r8, g8, b8, val);
// second method:
val = ((r8 & 0b11111000) << 8) | ((g8 & 0b11111100) << 3) | (b8 >> 3);
printf("%d, %d, %d, %u\n", r8, g8, b8, val);
// third method:
r5 = r8 * 31 / 255;
g6 = g8 * 63 / 255;
b5 = b8 * 31 / 255;
val = (r5 << 11) | (g6 << 5) | (b5);
printf("%d, %d, %d, %u\n", r8, g8, b8, val);