java 按位“&”就长了?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5017954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 09:04:16  来源:igfitidea点击:

Bitwise "& " on a long?

javaandroid

提问by Regis St-Gelais

I want to obtain the least 32 bits from a number of type long, so I perform bitwise operation "&" on the number with bits mask 0xFFFFFFFF, but the result is not correct, it still contains the other bits.

我想从一个long类型的数字中获取最少的32位,所以我对位掩码为0xFFFFFFFF的数字执行按位运算“&”,但结果不正确,它仍然包含其他位。

for example:

例如:

long a = 0x1234567890ab; 
long b = (a & 0xffffffff);

I expect the value of b to be 0x567890ab

我希望 b 的值是 0x567890ab

but in practice, it is still 0x1234567890ab

但实际上,它仍然是 0x1234567890ab

回答by axtavt

Try this:

试试这个:

long a = 0x1234567890ab;  
long b = (a & 0xffffffffL);

0xffffffffis a literal of type int, for performing &with longit's promoted to type longby sign extension, therefore it turns into 0xffffffffffffffff. To avoid sign extension you need to write it as a literal of type long: 0xffffffffL.

0xffffffff是 type 的文字int,为了执行&longlong通过符号扩展被提升为 type ,因此它变成0xffffffffffffffff. 为避免符号扩展,您需要将其写为类型为long:的文字0xffffffffL

回答by sargas

Does using 0xffffffffL make any difference?

使用 0xffffffffL 有什么不同吗?

I think what happens is that 0xffffffff gets upcasted to a long, and since both int and long are signed it tries to keep the same sign.

我认为发生的情况是 0xffffffff 被向上转换为 long,并且由于 int 和 long 都已签名,因此它会尝试保持相同的符号。

So, since 0xffffffff is -1 as an int, it gets converted to -1 as a long, or 0xffffffffffffffff

因此,由于 0xffffffff 作为 int 是 -1,因此它会被转换为 -1 作为 long,或 0xffffffffffffffff

回答by Scott M.

try doing a bitwise AND with a long value with some leading zeroes instead of a 32 bit value. right now you're basically doing nothing to the number.

尝试使用带有一些前导零而不是 32 位值的长值进行按位 AND 运算。现在你基本上没有对数字做任何事情。