Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
663 views
in Technique[技术] by (71.8m points)

java - Why does the xor operator on two bytes produce an 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...