18

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.

1 Answer 1

21

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).

Sign up to request clarification or add additional context in comments.

4 Comments

That does work, indeed. I thought it didn't because the input value was not the same as the output value. Still isn't. Don't know what extra bits are stored in there, but I guess they don't matter.
Keep in mind that this does not work with r/g/b/a being integers. One must cast them explicitly into byte before adding them together.
JS bitwise operators get and return 32 bit signed integer, so 255 << 24 become -16777216, the r part should be (r * (2 ** 24)), and you can't use | instead of +
One can use >>> 0 to get the signed integer, i.e.: 255 << 24 >>> 0 = 4278190080

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.