liveBook · Manning

Bit operation

As explained in Go in Action, Second Edition

A bitwise operation computes a result by manipulating the individual binary bits of integer operands.

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

How Go in Action, Second Edition covers it

How deep it goes
Defines six operators and explains bit clear, then descends into signed-versus-unsigned shifting and integer-width choices.
Examples
Uses an operator table and contrasts signed and unsigned right shifts to illustrate practical bit manipulation choices.
What it assumes
Assumes familiarity with integer values and operators while defining Go’s bitwise operator set and bit-clear behavior.
What you can do after
Apply it via Go’s integer operators while choosing sized unsigned types for predictable bit manipulation.
How it connects
Connects bit operations to integer types, unsigned integers, bit fields, type conversion, and bit shifting.

Also explained in

Compare how 6 books explain bit operation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Action, Second Edition. The section links point to the parts of the book it draws on.