I am trying to convert a decimal value back to an RGB value.
Assuming that this is the formula for compiling the decimal value
c = r*(255*255)+g*255+b
(For example rgb(16,120,78) adds up to 1071078)
How would one solve r, g and b without any "overflow"?
Thanks in advance!
No, RGB supports 256 values for each color and that is it.
Red, Green and Blue Hexadecimal numbers are used on web pages to set colors. The color is defined by its mix of Red, Green and Blue, each of which can be in the range: 0 to 255 (in decimal) , or. 00 to FF (in hexadecimal) A color can be made by mixing Red, Green and Blue, so it is called the "RGB Color System".
Knowing this, we can say a color is 255(r),127(g),25(b),255(a) you can do this: The equation is very basic math. 0 is 0 and 255 is 1, you simply take the number of bits in that channel and divide it by the maximum (255) to find it's normalized (decimal) value.
JavaScript supports the use of hexadecimal notation in place of any integer, but not decimals. As an example, the number 2514 in hex is 0x9D2, but there is no language-supported way of representing 25.14 as a hex number.
Use division, modulo (%
) and floor rounding:
var r = Math.floor(c / (256*256));
var g = Math.floor(c / 256) % 256;
var b = c % 256;
halex spotted the diffence in use of 255 and 256 in the code. You should (as Millie Smith pointed out) use 256 instead of 255 when you put the components together:
var c = r * (256*256) + g * 256 + b;
A color component can have a value from 0 to 255, so you need to multiply by 256 to keep the next component from overlapping the previous.
This Github link helps a lot, but I edited the code with this code to solve a problem with me:
// convert three r,g,b integers (each 0-255) to a single decimal integer (something
between 0 and ~16m)
function colourToNumber(r, g, b) {
return (r << 16) + (g << 8) + (b);
}
// convert it back again (to a string)
function numberToColour(number) {
const r = (number & 0xff0000) >> 16;
const g = (number & 0x00ff00) >> 8;
const b = (number & 0x0000ff);
//return [b, g, r];
return `rgb(${b},${g},${r})`;
}
my edited code make the RGB returns correctly like the color I set
Examples of mine:
color in decimal is: 11665407 this is yellow
color in decimal is: 11665329 this is green
please test booth codes with this example: stackblitz example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With