tags:

views:

95

answers:

2

I have a long and a short I want the bits from the short to overwrite the low order 16 bits of the long.

Ex (broken into 16bit chunks for readability):

> long = 0xffff 0xffff 0xffff 0xffff
> short= 0x1234
> 
> output = (long)0xffff 0xffff 0xffff 0x1234
+6  A: 
long l = ...;
short s = ...;
long n = (l & ~0xFFFF) | (s & 0xFFFFL);
erickson
As currently written, this will break if `s >= 0x8000`, as Java will sign-extend `s` when it converts it from `short` to `long` to perform the bitwise OR. See also the edit I just made on my answer.
bcat
Yes, that's true, I'll patch up mine too.
erickson
+7  A: 
static long foobar(long aLong, short aShort) {
    return aLong & 0xFFFFFFFFFFFF0000L | aShort & 0xFFFFL;
}

Note that you must AND the short value with 0xFFFFL here, otherwise sign extension will cause the code to break (all high bits in the result will be set, regardless of their original value in the long) if the short is greater than or equal to 0x8000.

bcat