简体   繁体   中英

What does this `^` operator mean in Dart?

What does this ^ operator mean in Dart?

int get hashCode => cityName.hashCode ^ temperatureCelsius.hashCode;

In many languages, including Dart, the ^ operator stands for a bitwise XOR operation.

What this does, conceptually, is to turn both of its operands into bit-strings of equal length and apply the exclusive-or logic to every pair of bits.

Example:

Let's say our inputs are the number 7 and the number 14. Here are their binary (bit-string) representations:

 7: 0111
14: 1110

In that case the result will be:

 9: 1001

In your example this seems to be used for creating a hash from two other hash values. That's the "default" way of combining two hash values, the reason being explained here:

Why is XOR the default way to combine hashes?

The ^ operator is a user-defined binary operator. A class can define it to mean whatever it wants. Some built-in Dart classes have a ^ operator, namely int and bool .

For bool , the ^ operator is the exclusive-or operation, the result is true if and only iff exactly one of the operands are true (and the other is then false because it must be a bool ).

For int , the ^ operator is the bitwise exclusive or operation. The integer numbers are interpreted as the bits of their two's complement representation, and the bits of the two operands at the same position are exclusive-or'ed so the result is 1 if and only if exactly one of the two bits is 1. Example:

  var x = 27;    // bits: ..0011011
  var y = 37;    // bits: ..0100101
  var z = x ^ y; // bits: ..0111110 - aka 62

Non-platform classes can also implement the operator, like in the fixnum package .

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