[英]What does this `^` operator mean in Dart?
What does this ^
operator mean in Dart?这个^
运算符在 Dart 中是什么意思?
int get hashCode => cityName.hashCode ^ temperatureCelsius.hashCode;
In many languages, including Dart, the ^
operator stands for a bitwise XOR operation.在许多语言中,包括 Dart, ^
运算符代表按位异或运算。
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 和数字 14。这是它们的二进制(位串)表示:
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.在您的示例中,这似乎用于从其他两个 hash 值创建 hash 。 That's the "default" way of combining two hash values, the reason being explained here:这是组合两个 hash 值的“默认”方式,原因在这里解释:
Why is XOR the default way to combine hashes? 为什么 XOR 是组合哈希的默认方式?
The ^
operator is a user-defined binary operator. ^
运算符是用户定义的二元运算符。 A class can define it to mean whatever it wants. class 可以将其定义为任何它想要的意思。 Some built-in Dart classes have a ^
operator, namely int
and bool
.一些内置的 Dart 类有一个^
运算符,即int
和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
).对于bool
, ^
运算符是异或运算,当且仅当仅当一个操作数为真时结果为true
(而另一个为false
,因为它必须是bool
)。
For int
, the ^
operator is the bitwise exclusive or operation.对于int
, ^
运算符是按位异或运算。 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: integer 数字被解释为它们的二进制补码表示的位,并且同一 position 处的两个操作数的位是异或,因此当且仅当两个位中的一个恰好为 1 时,结果为 1。 :
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 .非平台类也可以实现运算符,例如在fixnum package 中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.