David Parks
David Parks

Reputation: 32071

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

Upvotes: 6

Views: 1599

Answers (2)

erickson
erickson

Reputation: 269667

long l = ...;
short s = ...;
long n = (l & ~0xFFFF) | (s & 0xFFFFL);

Upvotes: 6

bcat
bcat

Reputation: 8941

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.

Upvotes: 7

Related Questions