Search code examples
c#mathcolorsradix

Base 10 number to 16 bit colour in C#


I'm trying to represent each of the possible 65,536 colours of the 16 bit colour depth as a base 10 integer, but I'm having trouble.

Essentially I need to convert a base 10 number to a Color object representing that colour in the 16 bit spectrum. I think that base is important here, but I can't decide what base to go to.


Solution

  • The 16 bit color space uses 5 bits for the red channel, 6 for green and 5 for the blue channel. You can extract the values for each channel using bitwise operations.

    int color = /* your 16 bit value here */
    
    int red = color & 31;
    int green = (color >> 5) & 63;
    int blue = color >> 11;
    

    To convert back, use

    int color = red | green << 5 | blue << 11;