& ^ =运算符有什么作用?

时间:2017-05-04 10:54:39

标签: go operators

我在Go语言本身的源代码中遇到了this line

small &^= 4096 - 1

我以前从未见过&^=运算符(在Go或C中) - 它有什么作用?

1 个答案:

答案 0 :(得分:0)

正如评论中提到的,&^ 是“位清晰”(AND NOT) 运算符,而 a &^= b 表示 a = (a &^= b)

Playground

package main

import (
    "fmt"
)

func main() {
    var x int64 = 0xdeadbeefface
    fmt.Printf("   x = %064b %012x\n", x, x)

    var y int64 = 0xffff0000
    fmt.Printf("   y = %064b %012x\n", y, y)

    x &^= y
    fmt.Printf("x&^y = %064b %012x\n", x, x)
}
   x = 0000000000000000110111101010110110111110111011111111101011001110 deadbeefface
   y = 0000000000000000000000000000000011111111111111110000000000000000 0000ffff0000
x&^y = 0000000000000000110111101010110100000000000000001111101011001110 dead0000face

还有small &^= 4096 - 1

4095 - 1 == 0b0000111111111111 开始,这意味着“将数字的 12 个最低有效位设置为零”。

func main() {
    small := 0xdeadbeefface
    fmt.Printf("             small : %064b %012x\n", small, small)
    small &^= 4096 - 1
    fmt.Printf("small &^= 4096 - 1 : %064b %012x\n", small, small)
}
             small : 0000000000000000110111101010110110111110111011111111101011001110 deadbeefface
small &^= 4096 - 1 : 0000000000000000110111101010110110111110111011111111000000000000 deadbeeff000