Sam McCreery
Sam McCreery

Reputation: 552

Integer and Long conversion

Say I want to create a long value which has two packed ints inside. I want to take my two ints and pack them side-by-side within the long. I can think of two different ways to achieve this, both of which I believe will work the same way:

int a = 0x7FFFFFFF;
int b = 0x10000000;
long x;

// Method one
x = (a & 0xFFFFFFFFL) << 32 | (b & 0xFFFFFFFFL);

// Method two
x = (long) (a << 32) | (long) a;

What's the difference between these two methods? Will they both produce the same result in all cases?

Upvotes: 1

Views: 178

Answers (1)

birkett
birkett

Reputation: 10091

The second method does not work. Apart from the typo, (it should end with long b), your a will not be affected by the shift (Thanks harold for correction). You have to convert before shifting.

int a = 0x7FFFFFFF;
int b = 0x10000000;
long x;

// Method one
x = (a & 0xFFFFFFFFL) << 32 | b;

// Method two
x = (((long)a) << 32) | b;

Also, in the second and first method, the casting of b is redundant. The conversion is done implicitly.

Both methods seem pretty similar. However, method 1 might do some unnecessary operation since it will perform an additional AND and conversion.

Method 1:

  • al <- a I2L
  • res <- al LAND 0xFFFFFFFFL
  • res2 <- res LSHL 32
  • bl <- b I2L
  • al OR bl

Method 2:

  • al <- a I2L
  • res2 <- al LSHL 32
  • bl <- b I2L
  • al OR bl

Upvotes: 1

Related Questions