Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

  1. Transform a single long into two integers that faithful contain its bit data
  2. Transform two integers back into a long that faithfully contains their bit data.

2 Answers

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 ints 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".

like image 139
Mr. Polywhirl Avatar answered Oct 27 '25 03:10

Mr. Polywhirl


int u,v
long n = u;
if (v < 0) { ++n; }
n <<= 32;
n += v;
like image 28
lkreinitz Avatar answered Oct 27 '25 02:10

lkreinitz



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!