Manipulate bits and shifts
Manipulate bits and shifts
Bitwise operators work on integer bits. & keeps bits set in both operands; | keeps bits set in either; ^ keeps bits set in exactly one; &^ clears bits of the left operand that are set in the right. Unary ^ complements bits. A bit mask is an integer whose set bits select positions.
package main
import "fmt"
func main() { var flags uint8 = 0b0101 var mask uint8 = 0b0010 flags |= mask fmt.Printf("%04b\n", flags) fmt.Println(flags&mask != 0) flags &^= mask fmt.Printf("%04b\n", flags)}OR sets the selected bit, AND tests whether it is present, and AND NOT clears it. XOR toggles selected bits. Using uint8 makes the example width explicit. The four-digit formatting here displays at least four bits, not the full eight-bit width.
Shift bits left and right
package main
import "fmt"
func main() { var n uint8 = 0b0011 fmt.Println(n<<2, n>>1) fmt.Printf("%08b\n", ^n) var signed int8 = -3 fmt.Println(signed >> 1)}Left shift moves bits toward higher positions; for unsigned fixed-width values bits beyond the width are discarded. Right shift of unsigned integers fills with zeros; signed right shift is arithmetic, so -3 >> 1 is -2, not integer division -3/2. Shift counts must be nonnegative; negative runtime counts panic. Choose explicit unsigned widths for predictable masks.
Try it locally
Start with uint8 flags = 0. Set bit 2 using 1 << 2, then toggle bit 0 using XOR. Print decimal and four-digit binary. Expected: 5 0101.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Expressions and Arithmetic 07: Manipulate bits and shifts
Check the lesson objective before moving on.
Which operation clears the bits selected by mask?
What is uint8(3) << 2?