简体   繁体   中英

Java, combining two integers to long results negative number

I am trying to combining two integers to a long in Java. Here is the code I am using:

Long combinedValue = (long) a << 32 | b;

When a = 0x03 and b = 0x1B56 ED23 , I am able to get the expected value ( combinedValue = 13343583523 in long).

However, when my a = 0x00 and b = 0xA2BF E1C7 , I get a negative value, -1567628857 , instead of 2730484167 . Can anyone explain why shifting an integer 0 by 32 bits causes the first 32 bits become 0xFFFF FFFF ?

Thanks

b is negative, too. That's what that constant means. What you probably want is ((long) a << 32) | (b & 0xFFFFFFFFL) ((long) a << 32) | (b & 0xFFFFFFFFL) .

When you OR (long) a << 32 with b , if b is an int then it will be promoted to a long because the operation must be done between two values of the same type. This is called a widening conversion.

When this conversion from int to long happens, b will be sign extended, meaning that if the top bit is set then it will be copied into the top 32 bits of the 64 bit long value. This is what causes the top 32 bits to be 0xffffffff .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM