简体   繁体   English

Java,将两个整数组合成长结果负数

[英]Java, combining two integers to long results negative number

I am trying to combining two integers to a long in Java. 我正在尝试将两个整数组合成Java中的long。 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). a = 0x03b = 0x1B56 ED23 ,我能够获得期望值(long combinedValue = 13343583523 )。

However, when my a = 0x00 and b = 0xA2BF E1C7 , I get a negative value, -1567628857 , instead of 2730484167 . 但是,当我的a = 0x00b = 0xA2BF E1C7 ,我得到的是负值-1567628857而不是2730484167 Can anyone explain why shifting an integer 0 by 32 bits causes the first 32 bits become 0xFFFF FFFF ? 谁能解释为什么将整数0移位32位会导致前32位变为0xFFFF FFFF

Thanks 谢谢

b is negative, too. b为负。 That's what that constant means. 那就是常量的意思。 What you probably want is ((long) a << 32) | (b & 0xFFFFFFFFL) 您可能想要的((long) a << 32) | (b & 0xFFFFFFFFL) ((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. 当对b (long) a << 32b ,如果b是一个int则它将提升为long因为必须在两个相同类型的值之间进行运算。 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. 当从intlong转换发生时, b将被符号扩展,这意味着如果设置了最高位,则它将被复制到64位long值的高32位中。 This is what causes the top 32 bits to be 0xffffffff . 这就是导致高32位为0xffffffff

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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