Search code examples
javascripttypescriptinthexdata-conversion

int32 to hex string not working.. Typescript


I have a int32 containing rgba values encoded in the following way:

values = [255, 255, 255, 255];
this.colorInt = ( values[0] << 24 ) | ( values[1] << 16 ) | ( values[2] << 8 ) | values[3];

in this case all values range from 0-255

Now when i try to convert this to a hex string like so:

this.colorInt.toString(16);

I want to get this: #FFFFFFFF but i get this: -1 I have seen many stackoverflow posts about this but I cant get it to work...

What am I doing wrong here?


Solution

  • This is because the integer -1 (base 10) = 11111111111111111111111111111111 (base 2)

    If you use bitwise operators, you'll see this issue, as it deals with 32 bit integers only.

    Other operators like multiplication would take care of this. As they are not bitwise operators, their calculation is not limited to 32 bit integers. You can use the following.

    this.colorInt = 255 + (255 * 2**8) + (255 * 2**16) + (255*2**24)
    this.colorInt.toString(16) // "ffffffff"
    

    Otherwise what I'd suggest as a more readable approach is

    function hexer(a,b,c,d){
        return ([a,b,c,d].map(x=>x.toString(16)).join(''))
    }
    hexer([255,255,255,255]) // "ffffffff"