What is a the quickest way to bitwise convert two ints to a long in java?

bit-manipulation, java, long-integer, type-conversion

Solution

No need to use Autoboxing (`Long`, `Integer`, etc.). Primitives work just fine. The following is the best you can do in the Java programming language.

Join

Combining two `int`s into a `long`

int lo; // Integer to fill lower bits
int hi; // Integer to fill upper bits
long val = (((long) hi) << 32) | (lo & 0xffffffffL);

Split

Retrieving the (upper) bits 31-16

int hi = (int) (val >> 32);

Retrieving the (lower) bits 15-0

int lo = (int) val;

Note:

Be aware of the difference between:

- `n >> 32` (Sign-extend right-shift)

- `n >>> 32` (Zero-fill right-shift)

Since Java used only signed bits, the `>>>` operator was introduced to handle integers as if they were "unsigned".

Problem

I've been using images to store data, since editing binary data through Paint.net is much friendlier than most hex editors. However, some of my data is long integers. Long integers are twice the size of a 32-bit integer in java, 64-bits. How does one get the long to two integers, and more importantly, back to a long when reading the image? Since Java does not have unsigned ints, the top bit of the integer or long is the negative sign bit, even though bit 32 (the lower integer/pixel) will be an ordinary bit in the long integer. Most methods of converting long to int discard the upper bits, as well, which will or may contain bitwise (binary) information! What I need to do is - Transform a single long into two integers that faithful contain its bit data - Transform two integers back into a long that faithfully contains their bit data.

Original source

Related problems