Search code examples
colorsbytebit

Convert 8 bit color to 24 bit color


I was wondering if I can convert an 8-bit RGB color (1 byte = single color) into a 24-bit RGB color ((8 bits = red, 8 bits = green, 8 bits = blue) = single color). Is there a way it can be done? (I don't mind having only 256 colors). Also, if it would be possible can it be written as a formula/function in Python?


Solution

  • def convert_8_to_24(byte):
        byte = int(byte, 16)
        red = (byte >> 5) * 32
        green = ((byte & 28) >> 2) * 32
        blue = (byte & 3) * 64
        return (red, green, blue)
    
    def convert_24_to_8(red, green, blue):
        byte = (floor((red / 32)) << 5) + (floor((green / 32)) << 2) + floor((blue / 64))
        byte = hex(byte)[2:]
        if len(byte) == 1:
            byte = "0" + byte
        return byte