gpt4 book ai didi

java - 并且按位运算得到负值

转载 作者:搜寻专家 更新时间:2023-10-31 20:11:08 25 4
gpt4 key购买 nike

我有这个代码:

 int code = 0x92011202;
int a = (code & 0xF0000000) >> 28;
int b = (code & 0x0F000000) >> 24;
// ..
int n = (code & 0x0000000F);

但如果 code 的最高有效位等于 1(从 9 到 F),则 a 为负值。所有其他变量 工作正常。

为什么会这样?

最佳答案

这在 The Java Tutorials 中有解释.

具体来说:

The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension.

Java 使用 2s 补码变量。您关心的关于 2s 补码的唯一方面是,如果最左边的位是 1,则数字是负数。带符号的移位保持符号,因此如果代码一开始是负的,它在移位后保持负数。

要修复您的程序,请使用 >>>,这是一个逻辑移位,忽略符号

关于java - 并且按位运算得到负值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27478272/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com