javascript转换问题(将rgb和rgba转换为十六进制) [英] javascript shifting issue (rgb and rgba to hex)
问题描述
我找到了RGB到十六进制转换器,并且我正在尝试制作RGBA到十六进制转换器.原始的 rgb2hex
函数有效,但新的 rgba2hex
函数无效.我究竟做错了什么?rgba函数返回gba,不返回r.
I found a RGB to hex converter and I'm trying to make a RGBA to hex converter. The original rgb2hex
function works but the new rgba2hex
function does not. What am I doing wrong? The rgba function is returning 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);
}
示例:
alert(rgb2hex(255, 155, 055));
alert(rgba2hex(255, 155, 055, 255));
当前输出: ff9b2d
和 9b2dff
预期输出: ff9b2d
和 ff9b2dff
推荐答案
您的问题是JavaScript中的按位数学运算上限为31位,因此您不能完全按原样进行操作.您需要使用普通的数学运算,而不是按位运算:
Your issue is that bitwise math in JavaScript caps out at 31 bits, so you can't quite do this as is. You need to use normal math ops, not bitwise ops:
// 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);
}
还解决了原始算法的一个问题,即如果第一个分量是<10,输出的位数不足.
Also fixed an issue with the original algorithm where if the first component is < 10, the output doesn't have enough digits.
无论如何,这还是行不通的...#ff9b2dff
不是有效的颜色,但是您可能不在乎?
Anyway, this won't work anyway... #ff9b2dff
isn't a valid color, but you may not care?
这篇关于javascript转换问题(将rgb和rgba转换为十六进制)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!