Search code examples
javascriptcolorshexparseint

convert from a color back to a number in javascript


I have an existing fn that does the following:

    public GetColor = (argb: number) => {

        var a = 1;// (argb & -16777216) >> 0x18; // gives me FF


        var r = (argb & 0xff0000) >> 0x10;
        var g = (argb & 0x00ff00) >> 0x8;
        var b = (argb & 0x0000ff);
        var curKendoColor = kendo.parseColor("rgba(" + r + "," + g + "," + b + "," + a + ")", false);

I would like to know the function I would need to return that back to a number.

for example if i have AARRGGBB of (FFFF0000) and I would like to get back to the number version that toColor would have derived from.

I would be ok with the unsigned version of the return number or the signed version. Unsigned would be -65536 but the unsigned would be fine as well (not sure what that number would be off top of my head now)

I tried to do this but the attempts all end out at 0 which i know is not correct: colorSend |= (parseInt(this.Color.substr(0,2),16) & 255) << 24; colorSend |= (parseInt(this.Color.substr(1, 2), 16) & 255) << 16; colorSend |= (parseInt(this.Color.substr(3, 2), 16) & 255) << 8;

the parseInt gives me the 255,0,0 that I think I would expect but the & and the shift logic does not seem correct because & zeros the integers out thus the result was 0


Solution

  • Ok I was able to get something that seems to work for me. I am simplifying it a bit but for the ARGB i can do something like

    val = "0xFFFF0000"
    val = parseInt(val, 16)
    if((val & 0x80000000) != 0)
    {
       val = val - 0x100000000;
    }
    

    So for example for Red with an A of FF I would get- -65536 or with unsigned I can omit the last part.