参见英文答案 >
Java – bit shifting with integers and bytes 3
>
Why can not I add two bytes and get an int and I can add two final bytes get a byte? 2
所以我来了一个关于按位运算符和位移的奇怪的行为.我试图通过使用位掩码更快地做一个小的检查,我来到这里:
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和hto工作有什么样的魔法?
编辑:或者这不完全是重复的
而且,由于我寻求理论上的答案(因为我已经明白我可以通过转换来编译我的代码)转移和其他bitwize操作如何确定它们的返回值,我相信这个问题可以补充Java – bit shifting with integers and bytes并为StackOverflow带来更多有趣的信息.