Go Reference ยท Operators
Go bitwise operators
Reference for Go bitwise operators &, |, ^ (xor and not) and &^ (AND NOT): integer-only operands, flags and masks, set, clear and toggle idioms, math/bits.
Bitwise operators act on each bit of integer operands. Go provides & (AND), | (OR), ^ (XOR when binary, bitwise NOT when unary) and &^ (AND NOT, "bit clear"). Together with the shifts << and >> they are used for flags, masks, hashing and compact data structures.
Both operands must have the same integer type. Results wrap within that type, so the width matters especially for the unary ^.
fmt.Println(0b1100&0b1010, 0b1100|0b1010, 0b1100^0b1010) // 8 14 6
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
x & y // AND x | y // OR x ^ y // XOR x &^ y // AND NOT: bits of x that are not set in y ^x // bitwise complement x &= y x |= y x ^= y x &^= y
| Operator | Rule per bit |
|---|---|
& |
1 if both bits are 1 |
| |
1 if either bit is 1 |
^ (binary) |
1 if the bits differ |
&^ |
1 if x is 1 and y is 0 |
^ (unary) |
flips every bit; for signed x equals -x - 1 |
Operands must be integers of identical type. Untyped constants adapt to the other operand; a constant that does not fit the type is a compile error.
Usage notes
- Flags. Declare bit flags with
1 << iota, then set with|=, clear with&^=, test with&, toggle with^=. - Precedence.
&,&^,<<,>>and*share the multiplication level;|,^,+and-the addition level. Comparisons bind looser, sox&1 == 1works, unlike in C, but parentheses still help. - No bitwise NOT operator
~. Go uses unary^. For unsigned types^xisMaxUint - x. - Signed values use two's complement, so bit operations on negative numbers act on their 64-bit (or type-width) representation.
- Booleans. These operators do not apply to booleans; see Logical operators.
- Library help.
math/bitsprovidesOnesCount,LeadingZeros,TrailingZeros,Len,RotateLeft,ReverseandReverseBytes. - Hex and binary literals (
0xFF,0b1010,0o17, with_separators) make masks readable. - Byte order is not defined by these operators; use
encoding/binaryto encode integers into bytes.