What does ^ do?

huangapple go评论67阅读模式
英文:

What does ^ do?

问题

我希望这个问题不会太愚蠢...我不知道在Go语言中^运算符是做什么用的,例如:

a := 3^500

起初我以为它可能是幂运算(pow),但它肯定不是。它也不是取模运算(%)。

我尝试查看文档和在Google上搜索,但不幸的是,Google不认为^是一个搜索词。

英文:

I hope this question is not too stupid... I have no idea what the ^ operator does in Go, e.g.

a := 3^500

At first I thought it must be pow but it most certainly is not. It's not mod (%) either.

I've tried looking through the doc and searching on Google, but unfortunately Google doesn't think ^ is a search term.

答案1

得分: 36

与大多数语言一样,caret 运算符是按位异或运算。您可以在整数上使用它。

相关的 Golang 文档

维基百科关于按位异或的说明

> 按位异或运算将两个等长的二进制模式进行逻辑异或操作。在每个对应位置上,如果只有第一个位为1或只有第二个位为1,则结果为1;如果两个位都为0或都为1,则结果为0。在这里,我们比较两个位,如果两个位不同,则结果为1,如果两个位相同,则结果为0。
>
> 按位异或运算可以用于反转寄存器中的特定位(也称为切换或翻转)。通过将某个位与1进行按位异或,可以切换该位。例如,给定位模式0010(十进制2),可以通过与一个在第二位和第四位位置上为1的位模式进行按位异或来切换第二位和第四位:
>
> 0010(十进制2)
> XOR 1010(十进制10)
> = 1000(十进制8)
>
> 这种技术可以用于操作表示布尔状态集的位模式。

将 @karmakaze 的评论添加到这个答案中,以提供更多有用的信息:

> 作为一元运算符,它是按位取反的。例如,^uint(0) 在32位机器上的结果是 0xffffffff,在64位机器上的结果更长。

英文:

As in most languages, the caret operator is a bitwise XOR. You use it on integers.

Relevant Golang documentation

Wikipedia on the bitwise xor :

> A bitwise XOR takes two bit patterns of equal length and performs the
> logical exclusive OR operation on each pair of corresponding bits. The
> result in each position is 1 if only the first bit is 1 or only the
> second bit is 1, but will be 0 if both are 0 or both are 1. In this we
> perform the comparison of two bits, being 1 if the two bits are
> different, and 0 if they are the same
>
> The bitwise XOR may be used to invert selected bits in a register
> (also called toggle or flip). Any bit may be toggled by XORing it with
> 1. For example, given the bit pattern 0010 (decimal 2) the second and fourth bits may be toggled by a bitwise XOR with a bit pattern
> containing 1 in the second and fourth positions:
>

     0010 (decimal 2)
 XOR 1010 (decimal 10)
   = 1000 (decimal 8)

> This technique may be used to manipulate bit patterns representing sets of
> Boolean states.

Adding the comment from @karmakaze to this answer for more helpful info:

>Also as a unary operator, it's bitwise not. e.g. ^uint(0) results in the uint value 0xffffffff for 32-bit machine and longer for a 64-bit machine.

huangapple
  • 本文由 发表于 2014年7月22日 23:01:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/24890912.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定