Negative values while converting hex color in rgba (JavaScript)

0

My problem is to convert a hexadecimal color string, with alpha value, and obtain the four channels R G B A. The lenght of the string is 8 (for example: 4faabbaa)

I've tried the following code, with bitwise operators, to convert the string and obtain the rgba.

var hex = "4faabbaa"; //In this case R is correct (79)

var hexint = parseInt(hex, 16);
var r = hexint >> 24;
var g = (hexint & 0x00FF0000) >> 16;
var b = (hexint & 0x0000FF00) >> 8;
var a = hexint & 0x000000FF;

The code works for all values of G B and A channels but, for some R values, returns negative values.

For example if I use:

var hex = "ccaabbaa"; //In this case returns a negative R (-52)

Returns a negative value for R

Why??

javascript
hex
data-conversion
rgba
asked on Stack Overflow Nov 18, 2017 by devpelux

1 Answer

0

The solution is to use >>> instead of >>, because the bit 0x80000000 stores the minus sign in 32bit signed integer values.

answered on Stack Overflow Jan 23, 2019 by devpelux • edited Nov 16, 2020 by devpelux

User contributions licensed under CC BY-SA 3.0