user1293081
user1293081

Reputation: 331

Convert long to two int and vice versa

How can I convert two 32 bit integers (int) to one 64 bit long and vice versa?

Upvotes: 25

Views: 16693

Answers (2)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272782

Ints to longs:

long c = ((long)a << 32) | ((long)b & 0xFFFFFFFFL);

I'll leave it as an exercise for the reader to perform the reverse calculation. But the hint is; use more bit-shifts and bit-masks.

(Edited as per comment by T. Murdock)

Upvotes: 2

Fuwjax
Fuwjax

Reputation: 2367

long c = (long)a << 32 | b & 0xFFFFFFFFL;
int aBack = (int)(c >> 32);
int bBack = (int)c;

In Java, you don't need quite so many parentheses, or any masking on the reverse calculation.

Upvotes: 51

Related Questions