Java: how to replace the last 16 bits with a long short

I have a long and short I want the bit from the short circuit to be overwritten by the low 16-bit long.

Ex (broken into 16 bits for readability):

> long = 0xffff 0xffff 0xffff 0xffff > short= 0x1234 > > output = (long)0xffff 0xffff 0xffff 0x1234 
+6
java bit-manipulation
source share
2 answers
 static long foobar(long aLong, short aShort) { return aLong & 0xFFFFFFFFFFFF0000L | aShort & 0xFFFFL; } 

Please note that a short short value is required here, otherwise the character extension will lead to a code break (all high bits will be set as a result, regardless of their initial value to long ), if short greater than or equal to 0x8000 .

+7
source share
 long l = ...; short s = ...; long n = (l & ~0xFFFF) | (s & 0xFFFFL); 
+6
source share

All Articles