Search code examples
c#mathcolorslogicradix

Converting a number to a colour


I'm trying to convert an integer, 0 to 65536, to a Color object in C#. Originally, I thought about creating a list of all the possible 16 bit Colors and addressing them with the integer, but this is very inefficient.

How can I get the ith possible 16 bit Color object?


Solution

  • A 16 bit color is normally made up of 5 bits of red, 6 bits of green and 5 bits of blue:

    rrrr rggg gggb bbbb
    

    Ref: Wikipedia: High color

    To turn that into a 24 bit color that the Color structure represents, you would extract the color components and convert them to the 0..255 range:

    int red = color >> 11;
    int green = (color >> 5) & 63;
    int blue = color & 31;
    
    red = red * 255 / 31;
    green = green * 255 / 63;
    blue = blue * 255 / 31;
    
    Color result = Color.FromArgb(red, green, blue);