java 为什么两个字节上的异或运算符会产生一个 int?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2003003/
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
Why does the xor operator on two bytes produce an int?
提问by defectivehalt
//key & hash are both byte[]
int leftPos = 0, rightPos = 31;
while(leftPos < 16) {
//possible loss of precision. required: byte, found: int
key[leftPos] = hash[leftPos] ^ hash[rightPos];
leftPos++;
rightPos--;
}
Why would a bitwise operation on two bytes in Java return an int? I know I could just cast it back to byte, but it seems silly.
为什么在 Java 中对两个字节进行按位运算会返回一个 int?我知道我可以将它转换回字节,但这似乎很愚蠢。
采纳答案by Michael Borgwardt
Because the language spec says so. It gives no reason, but I suspect that these are the most likely intentions:
因为语言规范是这样说的。它没有给出任何理由,但我怀疑这些是最有可能的意图:
- To have a small and simple set of rules to cover arithmetic operations involving all possible combinations of types
- To allow an efficient implementation - 32 bit integers are what CPUs use internally, and everything else requires conversions, explicit or implicit.
- 拥有一组小而简单的规则来涵盖涉及所有可能的类型组合的算术运算
- 为了允许有效的实现 - 32 位整数是 CPU 内部使用的,其他所有内容都需要显式或隐式转换。
回答by RzR
If it's correct and there are no value that can cause this loss of precision, in other words : "impossible loss of precision" the compiler should shut up ... and need to be corrected, and no cast should be added in this :
如果它是正确的并且没有可能导致这种精度损失的值,换句话说:“不可能的精度损失”,编译器应该关闭......并且需要更正,并且不应在此添加强制转换:
byte a = (byte) 0xDE;
byte b = (byte) 0xAD;
byte r = (byte) ( a ^ b);
回答by Victor Nicollet
There is no Java bitwise operations on two bytes. Your code implicitly and silently converts those bytes to a larger integer type (int), and the result is of that type as well.
两个字节没有 Java 按位运算。您的代码隐式地、静默地将这些字节转换为更大的整数类型 ( int),结果也属于该类型。
You may now question the sanity of leaving bitwise operations on bytes undefined.
您现在可能会质疑在未定义字节上保留按位运算的合理性。
回答by Licky Lindsay
This was somewhere down in the answers to one of the similar questions that people have already pointed out:
这是人们已经指出的类似问题之一的答案:
http://blogs.msdn.com/oldnewthing/archive/2004/03/10/87247.aspx
http://blogs.msdn.com/oldnewthing/archive/2004/03/10/87247.aspx

