Page 1 of 1

Convert 8-bit integer to Hex color value in JavaScript

Posted: 02 Dec 2020, 05:57
by Marius
I'm trying to convert 8-bit integer to Hex color value. (e.g. FFFFFF)
The 8-bit color integer is generated with the following formula:

Code: Select all

color = ( [red] * 65536) + ( [green] * 256) + ( [blue] * 1)
In C, it is done by:

Code: Select all

sprintf(colorbuf, "#%6.6x", color);
How can I convert this 8-bit integer value to Hex color value in Javascript?

Convert 8-bit integer to Hex color value in JavaScript

Posted: 02 Dec 2020, 12:01
by MarPlo
If you have an integer you can do with:

Code: Select all

color.toString(16)
And it will turn it in to a hex string.

Code: Select all

// White
color = (255 * 65536) + (255 * 256) + (255 * 1); // 16777215
color.toString(16); // 'ffffff'