I want to combine three characters into a short using bit shifting. This is for implementing the RGB565 color palette (where there are 5 bits for red, 6 for green, 5 for blue).
Here is my example program, i'm just missing a step in the middle i think where i need to do some anding.
#include <stdio.h>
int main( ){
unsigned char r, g, b;
unsigned short rgb;
r = 255; // 0xFF 1111 1111
g = 100; // 0x64 0110 0100
b = 50; // 0x32 0011 0010
r = r >> 3; // 0x31 0001 1111
g = g >> 2; // 0x19 0001 1001
b = b >> 3; // 0x06 0000 0110
//r = r & something; //
//g = g & something; //
//b = b & something; //
// Desired result:
// R G B
// 0xFB26 11111 011001 00110
rgb = r | g | b;
printf( "r 0x%x g 0x%x b 0x%x, rgb 0x%08x\n", r, g, b, rgb );
}
You can see my desired result at the end. Thanks for the help!
rgb = ((r & 0b11111000) << 8) | ((g & 0b11111100) << 3) | (b >> 3);
We shift r
left by 11 bits, g
left by 5 bits and bitwise OR these with b
shifted right by 3 bits. (NB: this assumes the values have already been correctly masked, if needed, to remove any unwanted bits.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With