简体   繁体   English

带有负字节的java中的XOR

[英]XOR in java with negative bytes

byte b = -0b0101^-0b0100;
System.out.println("Outputs "+b);
//Outputs 7

Why does this output 7 ( 0b111 ) when I was expecting 1 ( 0b001 )? 当我期待1( 0b001 )时,为什么输出7( 0b111 )?

Negative numbers are calculated according to "two's complement" arithmetic. 负数根据“二进制”算法计算。

-0b0101 = NOT(0000 0101) + 1 = 1111 1010 + 1 = 1111 1011
-0b0100 = NOT(0000 0100) + 1 = 1111 1011 + 1 = 1111 1100

If you XOR these you get: 如果您对这些进行异或,您会得到:

0000 0111 = 7

For presenting negative numbers in binary we use "Two's complement" 为了呈现二进制的负数,我们使用“Two's complement”

This is how you get negative binary numbers in java, check this link: How are integers internally represented at a bit level in Java? 这是你在java中获得负二进制数的方法,请查看以下链接: 如何在Java中的内部表示整数?

Then you get: -5 in binary is 11111011 -4 in binary is 11111100 -------- 00000111 = which is 7. That is why output is 7, hope it helps. 然后你得到:二进制中的-5是11111011 -4二进制是11111100 -------- 00000111 =这是7.这就是为什么输出是7,希望它有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM