简体   繁体   中英

Java: Why is it called bitwise exclusive or?

I am trying to understand how bitwise exclusive or works in java. So for example:

false ^ false = false
true ^ true = false  
true ^ false = true 
false ^ true = true

According to some posts here at SO, the size of boolean in java is jvm dependant. Typically boolean may be represented with 32 bits on the stack, 8 bits in the array.

So, why is it called bitwise if it is more than a byte on the stack?

According to the Java Language Specification there is no boolean bitwise operator but only boolean logical operators and integer bitwise operators .

15.22.1. Integer Bitwise Operators &, ^, and |

When both operands of an operator &, ^, or | are of a type that is convertible (§5.1.8) to a primitive integral type, binary numeric promotion is first performed on the operands (§5.6.2).

The type of the bitwise operator expression is the promoted type of the operands.

For &, the result value is the bitwise AND of the operand values.

For ^, the result value is the bitwise exclusive OR of the operand values.

For |, the result value is the bitwise inclusive OR of the operand values.

15.22.2. Boolean Logical Operators &, ^, and |

When both operands of a &, ^, or | operator are of type boolean or Boolean, then the type of the bitwise operator expression is boolean. In all cases, the operands are subject to unboxing conversion (§5.1.8) as necessary.

For &, the result value is true if both operand values are true; otherwise, the result is false.

For ^, the result value is true if the operand values are different; otherwise, the result is false.

For |, the result value is false if both operand values are false; otherwise, the result is true.

The ^ operator is overloaded. So if you use it on primitive boolean values, it work like logical XOR.

Bitwise refers to the size of the information they represent . Booleans represent 1 bit of information even though they might need more than 1 bit to be saved in memory.

It's called "bitwise" because it applies the logical XOR operation to each pair of bits on corresponding positions in the bit representation of the two operands (which can be any number, not only booleans).

Here's a simplified example for 8 bits:

9 (00001001) ^ 14 (00001110) = 7 (00000111).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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