简体   繁体   English

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

[英]What does the &^= operator do?

I came across this line in the source code for the Go language itself:我在 Go 语言本身的源代码中遇到了这一行

small &^= 4096 - 1

I have never seen the &^= operator before (either in Go or in C) - what does it do?我以前从未见过&^=运算符(在 Go 或 C 中) - 它有什么作用?

As the comments have mentioned, &^ is the "bit clear" ( AND NOT ) operator, and a &^= b means a = (a &^= b)正如评论所提到的, &^是“位清晰”( 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

And small &^= 4096 - 1 ?small &^= 4096 - 1

Since 4095 - 1 == 0b0000111111111111 , it would mean "set the 12 least significant bits of a number to zero".由于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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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