为什么两个字节的异或运算符会产生 int?
//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--;
}
为什么 Java 中两个字节的按位运算会返回 int?我知道我可以将其转换回字节,但这看起来很愚蠢。
//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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
因为语言规范是这么说的。它没有给出任何理由,但我怀疑这些是最可能的意图:
Because the language spec says so. It gives no reason, but I suspect that these are the most likely intentions:
如果它是正确的并且没有任何值会导致这种精度损失,换句话说:“不可能的精度损失”,编译器应该关闭......并且需要更正,并且不应在其中添加强制转换:
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 :
Java 中没有对两个字节进行按位运算。您的代码隐式且静默地将这些字节转换为更大的整数类型 (
int
),并且结果也是该类型。您现在可能会质疑未定义字节上的按位运算是否合理。
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.You may now question the sanity of leaving bitwise operations on bytes undefined.
这是人们已经指出的类似问题之一的答案中的某个地方:
http://blogs.msdn.com/oldnewthing/archive/2004/03/10/87247.aspx
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