Reputation: 552
Say I want to create a long
value which has two packed int
s inside. I want to take my two int
s 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
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:
Method 2:
Upvotes: 1