Javascript offset problem (rgb and rgba to hex)
I found an RGB to hex converter and I am trying to make an RGBA to hex converter. The original function rgb2hex
works, but the new function rgba2hex
does not work. What am I doing wrong? The rgba function returns gba, no r.
// convert RGB color data to hex
function rgb2hex(r, g, b) {
if (r > 255 || g > 255 || b > 255)
throw "Invalid color component";
return ((r << 16) | (g << 8) | b).toString(16);
}
// convert RGBA color data to hex
function rgba2hex(r, g, b, a) {
if (r > 255 || g > 255 || b > 255 || a > 255)
throw "Invalid color component";
return ((r << 32) | (g << 16) | (b << 8) | a).toString(16);
}
Example:
alert(rgb2hex(255, 155, 055)); alert(rgba2hex(255, 155, 055, 255));
Current output: ff9b2d
and9b2dff
Expected result: ff9b2d
andff9b2dff
source to share
Your problem is that the bitwise math in JavaScript closes down by 31 bits, so you can't do it the way it is. You need to use normal math operations, not bitwise operations:
// convert RGBA color data to hex
function rgba2hex(r, g, b, a) {
if (r > 255 || g > 255 || b > 255 || a > 255)
throw "Invalid color component";
return (256 + r).toString(16).substr(1) +((1 << 24) + (g << 16) | (b << 8) | a).toString(16).substr(1);
}
Also fixed an issue with the original algorithm where if the first component is <10 there are not enough digits in the output.
Anyway, it won't work ... #ff9b2dff
not a valid color, but you might care?
source to share
I feel like you are missing this idea here, the alpha value will dictate the opacity of the colors produced by the RGB posters, which means it will always be between 0 and 1 by standard convention, unless you are trying to make that value "normal" for your project.
The return value of your function seems to be hitting a limitation with the Javascript bit shifting mechanism. Return instead r.toString(16) + g.toString(16) + b.toString(16) + a.toString(16)
.
source to share