A bit operation manipulates individual bits in integer values. Go supports AND (&), OR (|), XOR (^), bit clear (&^), left shift (<<), and right shift (>>); the operators work only on integers. Go’s bit clear operator is unique among these: it clears every 1 bit present in its second operand. section 3.4
Choose integer representations deliberately when manipulating bits:
- Prefer unsigned integers when the value represents a bit field, because they avoid sign-bit concerns and shift in zeroes from the right. section 3.1.1
- Prefer sized unsigned types for bit manipulation, because their exact widths model memory more precisely than architecture-dependent uint. section 3.1.1
- Keep operands at compatible types; Go requires explicit conversion when integer types differ. section 3.4
- Account for signed right shifts, which use the sign bit, unlike unsigned right shifts, which shift in zeroes. section 3.1.1
Table 3.6 Bitwise operators (integers only)
| Operator |
Description |
|---|---|
|
|
AND |
|
|
OR |
|
|
XOR |
|
|
Bit clear |
|
|
Shift left |
|
|
Shift right |
Use the operator table to compare AND, OR, XOR, bit clear, and shift operations at a glance. section 3.4





