Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a 32 bit Integer into 4 8 bit Integers

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:

  1. Creating 4 Integer values from 0 to 255 and store them in a 32 bit Integer?

  2. Unpacking the 4 8 bit Integer values from the 32 bit Integer?

Thanks!

like image 618
jared-nelsen Avatar asked Oct 21 '25 15:10

jared-nelsen


1 Answers

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.

like image 74
Andy Turner Avatar answered Oct 23 '25 05:10

Andy Turner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!