Skip to content Skip to sidebar Skip to footer

Javascript Shifting Issue (rgb And Rgba To Hex)

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? Th

Solution 1:

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 hexfunctionrgba2hex(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, the output doesn't have enough digits.

Anyway, this won't work anyway... #ff9b2dff isn't a valid color, but you may not care?

Solution 2:

RGB to HEX

rgb(025594)
 rgb(0, 255, 94)

RGBA to HEX

rgba(255,25,2,0.5)
 rgba(255252 / 0.5)
 rgba(50%,30%,10%,0.5)
 rgba(50%,30%,10%,50%)
 rgba(50%30%10% / 0.5)
 rgba(50%30%10% / 50%)

DEMO - CODEPEN.IO

Post a Comment for "Javascript Shifting Issue (rgb And Rgba To Hex)"