Bitwise and Shift Operators
How to use Go's bitwise and shift operators to manipulate individual bits of integers, with clear examples and common mistakes
Go provides operators that let you work with the binary representation of integers. Instead of adding or comparing whole numbers, these operators let you inspect, set, or move individual bits. They are fundamental for low-level programming, cryptography, permissions systems, and any situation where you need to pack multiple flags into a single integer.
All bitwise and shift operators in Go work on integer types only: int, uint, and their sized variants. You cannot use them on floating-point numbers, strings, or booleans. The result of a bitwise or shift expression is always the same type as the left operand.
The two pages below cover each family in detail.
Understanding Bitwise Operators
The bitwise operators are & (AND), | (OR), ^ (XOR, and NOT when used with one operand), and &^ (AND NOT, or bit clear). They are the tools for building and inspecting bitmasks: set flags with |, clear them with &^, toggle them with ^, and test them with &. Note that ^5 is -6, because integers use two's complement; on a 64-bit platform int is 64 bits wide, so the complement is 64 bits of flipped bits.
Shift Operators
The shift operators are << (left) and >> (right). A left shift by n multiplies by 2 to the power of n; a right shift divides, with zeros filling the left for unsigned types and the sign bit copied for signed types. The shift count may be a signed integer, which has been legal since Go 1.13, but a negative count at runtime panics. There is no upper limit on the shift count: shifting a value by its full bit width or more is deterministic, giving 0 for left shifts and for right shifts of non-negative values, and -1 for right shifts of negative values.
Summary
Bitwise and shift operators give you direct control over the binary representation of integers. Go's set includes the familiar AND, OR, XOR, and shifts, plus a dedicated bit-clear operator and a unified ^ for both XOR and NOT. The most important practical takeaways are that signed right shifts preserve sign, that shift counts may be signed but never negative at runtime, and that overshifting is defined behavior, never a panic.
Bitwise Operators
Understand Go's bitwise AND, OR, XOR, NOT, and AND NOT operators, how they manipulate individual bits, and common use cases.
Shift Operators
Understand Go's left shift and right shift operators, how they manipulate bits, relate to multiplication and division by powers of two.