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

I have a long, short time

Ex (divided into 16 bit blocks for ease of reading):

> long = 0xffff 0xffff 0xffff 0xffff
> short= 0x1234
> 
> output = (long)0xffff 0xffff 0xffff 0x1234

Solution

static long foobar(long aLong,short aShort) {
static long foobar(long aLong,short aShort) {
    return aLong & 0xFFFFFFFFFFFF0000L | aShort & 0xFFFFL;
}

Please note that 0xffffl must be used with the short value here, otherwise the sign extension will cause code interruption (if short is greater than or equal to 0x8000, all high bits in the result will be set regardless of their original values in long)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>