Skip to content

Instantly share code, notes, and snippets.

@ajfisher
Created May 30, 2012 06:56
Show Gist options
  • Save ajfisher/2834170 to your computer and use it in GitHub Desktop.
Save ajfisher/2834170 to your computer and use it in GitHub Desktop.
Convert an 888 RGB value to 565 hex
# Author: Andrew Fisher
# Version: 0.1
# Date: 30/05/2012
# Licence: BSD
# This python converts an rgb value expressed in 8 bit values (eg 255, 128, 0) and returns a hex value that
# has been converted to 565 format. This was highly useful when I was playing with some Arduino
# stuff requiring 16 bit LCD designs and couldn't remember the hex layout.
def rgb_hex565(red, green, blue):
# take in the red, green and blue values (0-255) as 8 bit values and then combine
# and shift them to make them a 16 bit hex value in 565 format.
print ("0x%0.4X" % ((int(red / 255 * 31) << 11) | (int(green / 255 * 63) << 5) | (int(blue / 255 * 31))))
@joranmulderij
Copy link

For me it gave the wrong value, changing around the red and blue values. Changing blue to red and red to blue did the job for me. This was for my 1.8`128x160 RGB TFT LCD display. By the way, thanks for the code.

@tigercoding56
Copy link

Ty it still helps people (like me)

@jimf99
Copy link

jimf99 commented May 27, 2024

Thank You, bit shifting has been a challenge for me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment