Decimal To Rgb In Javascript And Php
Solution 1:
Use division, modulo (%
) and floor rounding:
var r = Math.floor(c / (256*256));
var g = Math.floor(c / 256) % 256;
var b = c % 256;
Edit:
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.
Solution 2:
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)
functioncolourToNumber(r, g, b) {
return (r << 16) + (g << 8) + (b);
}
// convert it back again (to a string)functionnumberToColour(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: 11665407this is yellow
color in decimal is: 11665329this is green
please test booth codes with this example: stackblitz example
Solution 3:
For starters, your formula for computing the decimal value looks off. 255 isn't a power of 16 (or even 2); if you want to shift a hex digit left, like what multiplying by powers of 10 does under decimal, you want to multiply by 16^n, where n is the number of places to shift it left.
Here's our new RGB to decimal formula:
c = r * 16^4 + g * 16^2 + b
So, supposing we have c, the decimal representation of an RGB color code, we solve for r, g, b:
b = c % 256g_0 = (c % 65536 - b)
r_0 = c - g_0 - b
g = g_0 / 256r = r_0 / 65536
These are all integer operations, so they should be fast, but I can't assure you the interpreter will handle them that way. As a function:
function c_to_rgb(c){
var b =c% 256,
g_0 = (c %65536- b),
r_0 =c- g_0 - b,
g = g_0 /256,
r = r_0 /65536;
return[r, g, b];
}
Solution 4:
I managed to solve it that way
getRGBFromDecimal(number) {
var b = Math.floor(number / (256*256));
var g = Math.floor(number / 256) % 256;
var r = number % 256;
return`RGB(${r},${g},${b})`;
}
Post a Comment for "Decimal To Rgb In Javascript And Php"