Converting rgba values into one integer in Javascript

skerit picture skerit · Jul 30, 2013 · Viewed 11.7k times · Source

I can already convert 32bit integers into their rgba values like this:

pixelData[i] = {
        red: pixelValue >> 24 & 0xFF,
        green: pixelValue >> 16 & 0xFF,
        blue: pixelValue >> 8 & 0xFF,
        alpha: pixelValue & 0xFF
    };

But I don't really know how to reverse it.

Answer

MightyPork picture MightyPork · Jul 30, 2013

To reverse it, you just have to combine the bytes into an integer. Simply use left-shift and add them, and it will work.

var rgb = (red << 24) + (green << 16) + (blue << 8) + (alpha);

Alternatively, to make it safer, you could first AND each of them with 0xFF:

var r = red & 0xFF;
var g = green & 0xFF;
var b = blue & 0xFF;
var a = alpha & 0xFF;

var rgb = (r << 24) + (g << 16) + (b << 8) + (a);

(You may use bitwise OR | instead of + here, the outcome will be the same).