Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How to replace last 16 bits of a long with a short

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
like image 245
David Parks Avatar asked Aug 25 '10 01:08

David Parks


2 Answers

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.

like image 138
bcat Avatar answered Sep 19 '22 01:09

bcat


long l = ...;
short s = ...;
long n = (l & ~0xFFFF) | (s & 0xFFFFL);
like image 41
erickson Avatar answered Sep 18 '22 01:09

erickson