user200783
user200783

Reputation: 14348

Why does Go have a "bit clear (AND NOT)" operator?

Why does Go have &^, the "bit clear (AND NOT)" operator?

Is there ever any difference between a &^ b and a & ^b?

Upvotes: 9

Views: 2740

Answers (1)

jussius
jussius

Reputation: 3274

There's a subtle difference that makes dealing with literals and untyped constants easier with the explicit bit clear operator.

Untyped integers have their default type as int so something like a := uint32(1) & ^1 is illegal as ^1 is evaluated first and it's evaluated as ^int(1), which equals -2. a := uint32(1) &^ 1 is legal however as here 1 is evaluated as uint32, based on the context.

There could also be some performance gains in having an explicit bit clear, but I'm not too sure about that.

Upvotes: 15

Related Questions