RGB888 - RGB565 / Bit Shift

I want to combine three characters into a short bit offset. This is for implementing the RGB565 color palette (where there are 5 bits for red, 6 for green, 5 for blue).

Here is my sample program, I just skipped a step in the middle, I think where I need to make some statements.

#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: // RGB // 0xFB26 11111 011001 00110 rgb = r | g | b; printf( "r 0x%xg 0x%xb 0x%x, rgb 0x%08x\n", r, g, b, rgb ); } 

At the end you can see my desired result. Thanks for the help!

+7
source share
2 answers
 rgb = ((r & 0b11111000) << 8) | ((g & 0b11111100) << 3) | (b >> 3); 

We will shift r left by 11 bits, g left by 5 bits and the bitwise OR by means of b shifted to the right by 3 bits. (NB: this assumes the values ​​have already been masked correctly, if necessary, to remove any unwanted bits.)

+13
source

Thanks for the A2A. I also ran into the same problem. The code below will help you.

 unsigned int r,g,b; // Pixel data in the RGB unsigned char x1,x2; // The container for resulting 2 bytes x1 = (r & 0xF8) | (g >> 5); // Take 5 bits of Red component and 3 bits of G component x2 = ((g & 0x1C) << 3) | (b >> 3); // Take remaining 3 Bits of G component and 5 bits of Blue component 

You can find the python program on GIThub. https://github.com/ajay126z/RGB888ToRGB565-Converter

0
source

All Articles