【发布时间】:2014-03-07 09:12:09
【问题描述】:
所以我遇到了关于按位运算符和位移的奇怪行为。我试图通过使用位掩码更快地进行小检查,但遇到了这个问题:
public class Weirdness {
private final static int constant = 3;
private static int notConstant = 3;
public void stuff() {
byte a = 0b1 << 3;
byte b = 0b1 << (int) 3;
byte c = 0b1 << constant;
byte d = 0b1 << notConstant; //error
byte e = 0b1 << getAnInt(); //error
byte f = 0b1 << getAFinalInt(); //error
int i = 3;
byte g = 0b1 << i; //error
final int j = 3;
byte h = 0b1 << j;
}
public static int getAnInt() {
return 3;
}
public static final int getAFinalInt() {
return 3;
}
}
a、b、c和h不给出编译错误;但是d、e、f 和g 可以。编译器要求显式转换为byte 或将最后一个变量声明为int。我也注意到 bitwize & 和 | 的类似行为。
有人能解释一下这里发生了什么吗?
为a、b、c 和h 工作的编译器有什么魔力?
编辑:或者这不完全是重复的
我相信这个问题与Why can not I add two bytes and get an int and I can add two final bytes get a byte? 不同,因为导致有趣行为的是编译器如何优化按位移位操作。
而且由于我寻求一个理论上的答案(因为我已经明白我可以通过强制转换来编译我的代码)移位和其他 bitwize 操作如何确定它们的返回值,我相信这个问题可以补充 Java - bit shifting with integers and bytes 并带来更多StackOverflow 的有趣信息。
【问题讨论】:
-
Rohit 的答案是我认为的你正在寻找的东西