I am working with video data in Java and wish to store four 8 bit integers in a 32 bit Integer. In other words I would like to pack the R, G, B, and A values from 0 to 255 into a single 32 bit Integer.
How can I go about:
Creating 4 Integer values from 0 to 255 and store them in a 32 bit Integer?
Unpacking the 4 8 bit Integer values from the 32 bit Integer?
Thanks!
Packing:
int rgba = (a << 24) | (b << 16) | (g << 8) | r;
<< is the left shift operator; | is the bitwise or operator.
Unpacking:
int r = rgba & 0xff;
int g = (rgba >> 8) & 0xff;
int b = (rgba >> 16) & 0xff;
int a = (rgba >> 24) & 0xff;
>> is the (signed *) right shift operator; & is the bitwise and operator.
Obviously, you can pack/unpack them in any order you desire.
(*) You can use either the signed or unsigned (>>>) right shift here. It makes no difference to the result in this case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With