Search code examples
javascriptcolorsrgb24-bit

How to convert RGB24 to RGB for web?


I have some colors in RGB24 format, for example: 1581613 How to convert it to RGB for web usage? If I understand correctly, the format is as follows RRRGGBB.

Last code i've trying to run is:

const color = 1581613;

const red   = (color >> 5) * 255 / 7;
const green = ((color >> 2) & 0x07) * 255 / 7;
const blue  = (color & 0x03) * 255 / 3;

But my attempts did not lead to success.


Solution

  • I'm guessing a lot here, but here goes:

    const color = 1581613;
    
    const red   = (color >> 16) & 255;
    const green = (color >> 8) & 255;
    const blue  = color & 255;
    
    const hex = red.toString(16) + green.toString(16) + blue.toString(16);
    
    document.write(JSON.stringify({rgb: [red, green, blue], hex }, null, 2));