Suppressing sign-extension when upcasting or shifting in Java -
i have feeling rather trivial question, i'm stumped. in application i'm keying things in lookup table pair of ints. thought easier concatenate 2 ints 1 long , use single long key instead. coming c background, hoping work:
int a, b; long l = (long)a << 32 | b;
my attempts replicate in java have frustrated me. in particular, because there no unsigned integral types, can't seem avoid automatic sign-extension of b (a gets left-shifted irrelevant). i've tried using b & 0x00000000ffffffff
surprisingly has no effect. tried rather ugly (long)b << 32 >> 32
, seemed optimized out compiler.
i hoping strictly using bit manipulation primitives, i'm starting wonder if need use sort of buffer object achieve this.
i use utility class with
public static long compose(int hi, int lo) { return (((long) hi << 32) + unsigned(lo)); } public static long unsigned(int x) { return x & 0xffffffffl; } public static int high(long x) { return (int) (x>>32); } public static int low(long x) { return (int) x; }
for int x, y
(negative or not)
high(compose(x, y)) == x low(compose(x, y)) == y
holds , long z
compose(high(z), low(z)) == z
holds, too.
Comments
Post a Comment