为什么两个字节的异或运算符会产生 int?

发布于 2024-08-17 06:21:39 字数 382 浏览 5 评论 0原文

        //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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

捂风挽笑 2024-08-24 06:21:39

因为语言规范是这么说的。它没有给出任何理由,但我怀疑这些是最可能的意图:

  • 拥有一组小而简单的规则来涵盖涉及所有可能的类型组合的算术运算
  • 为了允许有效的实现 - 32 位整数是 CPU 内部使用的,其他一切都需要显式或隐式转换。

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.
烟织青萝梦 2024-08-24 06:21:39

如果它是正确的并且没有任何值会导致这种精度损失,换句话说:“不可能的精度损失”,编译器应该关闭......并且需要更正,并且不应在其中添加强制转换:

byte a = (byte) 0xDE; 
byte b = (byte) 0xAD;
byte r = (byte) ( a ^ b);

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);
孤者何惧 2024-08-24 06:21:39

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.

婴鹅 2024-08-24 06:21:39

这是人们已经指出的类似问题之一的答案中的某个地方:

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文