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??
The solution is to use >>>
instead of >>
, because the bit 0x80000000 stores the minus sign in 32bit signed integer values.
User contributions licensed under CC BY-SA 3.0