Bit manipulation
suggest changeBit manipulation means working with the individual bits of an integer: testing and setting flags, packing several small values into one integer, decoding binary file formats and network protocols, or writing compact data structures like bit sets.
Go has everything you need for that:
- bitwise operators
&,|,^,&^and shifts<<,>> - binary literals like
0b1010_0110and the%bformat verb - package
math/bitsfor counting, finding and rotating bits; these functions compile to single CPU instructions where available - package
encoding/binaryfor reading and writing multi-byte integers in a given byte order
The operators themselves, their precedence and bit flags with iota are introduced in Operators. This article shows how to use them in practice.
Bit manipulation is easiest on unsigned integers (uint8, uint16, uint32, uint64, uint). Right shift of an unsigned value always fills with zeros, and there are no surprises with the sign bit. Use signed types only when the value really is signed.
Writing and printing binary numbers
package main
import (
"fmt"
"strconv"
)
func main() {
x := 0b1010_0110 // binary literal, _ is a digit separator
fmt.Println(x)
fmt.Printf("%b\n", x) // binary
fmt.Printf("%012b\n", x) // pad with zeros to 12 digits
fmt.Printf("%#b\n", x) // with 0b prefix
fmt.Printf("%#x %#o %#X\n", x, x, x)
var b uint8 = 5
fmt.Printf("%08b\n", b)
s := strconv.FormatUint(0xF0F0, 2)
fmt.Println(s)
n, err := strconv.ParseUint("0b1111_0000", 0, 8) // base 0: prefix and _ allowed
fmt.Println(n, err)
n, err = strconv.ParseUint("11110000", 2, 8)
fmt.Println(n, err)
n, err = strconv.ParseUint("111100001", 2, 8) // doesn't fit in 8 bits
fmt.Println(n, err)
}
166
10100110
000010100110
0b10100110
0xa6 0246 0XA6
00000101
1111000011110000
240 <nil>
240 <nil>
255 strconv.ParseUint: parsing "111100001": value out of range
Things to notice:
0b(or0B) starts a binary literal._can be used between digits to make long literals readable:0b1010_0110,0xFFFF_0000.%bprints binary digits. Use a width with a0flag (%08b,%032b) to see all bits of a value, including leading zeros.%#badds the0bprefix,%#xadds0x.strconv.FormatUint(x, 2)returns binary digits as a string.strconv.ParseUint(s, 2, bitSize)parses binary digits. With base0the base is taken from the prefix (0b,0o,0x) and_separators are allowed. When the value doesn't fit inbitSizebits you get the maximum value and an error.
Set, clear, toggle and test a single bit
To work with bit n (counting from 0, the least significant bit), build a mask 1 << n:
| Operation | Expression |
|---|---|
| set bit n | x | 1<<n |
| clear bit n | x &^ (1 << n) |
| toggle bit n | x ^ 1<<n |
| test bit n | x&(1<<n) != 0 |
With generics one set of functions works for every unsigned type:
package main
import "fmt"
type Unsigned interface {
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}
func SetBit[T Unsigned](x T, n uint) T { return x | 1<<n }
func ClearBit[T Unsigned](x T, n uint) T { return x &^ (1 << n) }
func ToggleBit[T Unsigned](x T, n uint) T { return x ^ 1<<n }
func HasBit[T Unsigned](x T, n uint) bool { return x&(1<<n) != 0 }
func main() {
var x uint8 = 0b0000_0101
x = SetBit(x, 7)
fmt.Printf("%08b\n", x)
x = ClearBit(x, 0)
fmt.Printf("%08b\n", x)
x = ToggleBit(x, 1)
fmt.Printf("%08b\n", x)
fmt.Println(HasBit(x, 2), HasBit(x, 3))
// works with any unsigned type, including named ones
var y uint64
y = SetBit(y, 63)
fmt.Printf("%#x\n", y)
}
10000101
10000100
10000110
true false
0x8000000000000000
&^ is Go's "AND NOT" (bit clear) operator. x &^ m does the same as x & ^m, in one operator. In C you would write x & ~m.
The ~uint8 in the constraint means "any type whose underlying type is uint8", so the functions also work with named types like type Flags uint8.
Masks and bit fields
A mask with the low n bits set is 1<<n - 1. For example 1<<5 - 1 is 0b11111. Shifting a mask left moves it to the bit field you're interested in.
To read a field: shift the value right so that the field starts at bit 0, then AND with a mask. To write a field: clear the old bits with &^, then OR in the new value:
package main
import "fmt"
// mask returns a value with the low n bits set
func mask(n uint) uint32 {
return 1<<n - 1
}
// getField extracts width bits starting at bit shift
func getField(x uint32, shift, width uint) uint32 {
return (x >> shift) & mask(width)
}
// setField replaces width bits starting at bit shift with v
func setField(x uint32, shift, width uint, v uint32) uint32 {
m := mask(width) << shift
return x&^m | (v<<shift)&m
}
func main() {
fmt.Printf("%08b\n", mask(5))
x := uint32(0b1011_0110_1100)
fmt.Printf("%04b\n", getField(x, 4, 4)) // bits 4..7
x = setField(x, 4, 4, 0b0001)
fmt.Printf("%012b\n", x)
x = setField(x, 4, 4, 0xFF) // extra bits of v are dropped
fmt.Printf("%012b\n", x)
}
00011111
0110
101100011100
101111111100
setField masks v after shifting it, so a value that is too large for the field can't corrupt neighbouring bits.
Go has no bit-field struct members like C (unsigned r : 5;). When you need to pack values tightly, for example to match a hardware register or a file format, use an integer and accessor methods.
Packing several values into one integer
A common example is a 32-bit RGBA color: 8 bits each for red, green, blue and alpha:
package main
import "fmt"
type RGBA uint32
func NewRGBA(r, g, b, a uint8) RGBA {
return RGBA(uint32(r)<<24 | uint32(g)<<16 | uint32(b)<<8 | uint32(a))
}
func (c RGBA) R() uint8 { return uint8(c >> 24) }
func (c RGBA) G() uint8 { return uint8(c >> 16) }
func (c RGBA) B() uint8 { return uint8(c >> 8) }
func (c RGBA) A() uint8 { return uint8(c) }
func (c RGBA) WithAlpha(a uint8) RGBA {
return c&^0xFF | RGBA(a)
}
func main() {
c := NewRGBA(0x12, 0x34, 0x56, 0xFF)
fmt.Printf("%#08x\n", uint32(c))
fmt.Println(c.R(), c.G(), c.B(), c.A())
c = c.WithAlpha(0x80)
fmt.Printf("%#08x\n", uint32(c))
}
0x123456ff
18 52 86 255
0x12345680
Converting to a smaller integer type keeps only the low bits, so uint8(c >> 16) is the green byte. There's no need for & 0xFF.
When packing, convert each byte to uint32 before shifting. r << 24 with r of type uint8 shifts all the bits out of the 8-bit value and gives 0.
Classic bit tricks
Some bit-level idioms come up again and again:
package main
import (
"fmt"
"math/bits"
)
func isPowerOfTwo(x uint64) bool {
return x != 0 && x&(x-1) == 0
}
// nextPowerOfTwo returns the smallest power of 2 >= x (for x >= 1)
func nextPowerOfTwo(x uint64) uint64 {
if x <= 1 {
return 1
}
return 1 << bits.Len64(x-1)
}
// alignUp rounds x up to a multiple of align, which must be a power of 2
func alignUp(x, align uint64) uint64 {
return (x + align - 1) &^ (align - 1)
}
func main() {
for _, x := range []uint64{0, 1, 6, 8, 1024} {
fmt.Print(isPowerOfTwo(x), " ")
}
fmt.Println()
for _, x := range []uint64{1, 5, 8, 9, 1000} {
fmt.Print(nextPowerOfTwo(x), " ")
}
fmt.Println()
fmt.Println(alignUp(13, 8), alignUp(16, 8), alignUp(4097, 4096))
x := uint8(0b0110_1000)
fmt.Printf("lowest set bit: %08b\n", x&-x)
fmt.Printf("clear lowest set bit: %08b\n", x&(x-1))
fmt.Printf("set lowest clear bit: %08b\n", x|(x+1))
fmt.Printf("keep low 4 bits: %08b\n", x&0x0F)
// x % 8 and x / 8 for unsigned x
y := uint(1234)
fmt.Println(y%8, y&7, y/8, y>>3)
}
false true false true true
1 8 8 16 1024
16 16 8192
lowest set bit: 00001000
clear lowest set bit: 01100000
set lowest clear bit: 01101001
keep low 4 bits: 00001000
2 2 154 154
How they work:
x & (x-1)clears the lowest set bit. Subtracting 1 flips the lowest set bit and all the zeros below it. A power of two has exactly one set bit, sox&(x-1) == 0tests for it.0has no set bits, so it needs a separate check.x & -xisolates the lowest set bit. For unsigned types-xis the two's complement^x + 1, which is allowed in Go and wraps around.x | (x+1)sets the lowest clear bit.- for a power of two
m,x % mequalsx & (m-1)andx / mequalsx >> log2(m). This only holds for unsigned (or non-negative) values. The compiler already does this optimization whenmis a constant, so writex % 8andx / 8for readability. alignUprounds up to a multiple of a power of two: addalign-1, then clear the low bits. Memory allocators and file formats with aligned blocks use this.nextPowerOfTwousesbits.Len64, which returns the number of bits needed to represent a value. It's simpler and faster than a loop.
Avoid "clever" tricks that don't buy anything, like swapping two variables with three XORs. In Go a, b = b, a is clearer and just as fast.
Package math/bits
math/bits has functions for unsigned integers in 8, 16, 32 and 64 bit sizes, plus versions without a suffix for uint:
package main
import (
"fmt"
"math/bits"
)
func main() {
var x uint16 = 0b0000_0110_1001_0000
fmt.Println("OnesCount: ", bits.OnesCount16(x))
fmt.Println("LeadingZeros: ", bits.LeadingZeros16(x))
fmt.Println("TrailingZeros:", bits.TrailingZeros16(x))
fmt.Println("Len: ", bits.Len16(x))
fmt.Printf("Reverse: %016b\n", bits.Reverse16(x))
fmt.Printf("ReverseBytes: %016b\n", bits.ReverseBytes16(x))
fmt.Printf("RotateLeft 4: %016b\n", bits.RotateLeft16(x, 4))
fmt.Printf("RotateRight 4: %016b\n", bits.RotateLeft16(x, -4))
fmt.Println(bits.TrailingZeros16(0), bits.Len16(0)) // zero is special
fmt.Println("UintSize:", bits.UintSize)
}
OnesCount: 4
LeadingZeros: 5
TrailingZeros: 4
Len: 11
Reverse: 0000100101100000
ReverseBytes: 1001000000000110
RotateLeft 4: 0110100100000000
RotateRight 4: 0000000001101001
16 0
UintSize: 64
OnesCountcounts set bits ("population count"). Use it to compute the size of a bit set or the Hamming distance between two values:bits.OnesCount64(a ^ b).LeadingZeroscounts zero bits above the highest set bit;TrailingZeroscounts zero bits below the lowest set bit. For0both return the bit size of the type.Lenis the number of bits needed to represent the value.bits.Len(x) - 1is the floor of log2(x) forx > 0.Len(0)is 0.Reversereverses the order of bits.ReverseBytesreverses the order of bytes (byte swapping, i.e. converting between big and little endian).RotateLeftrotates bits: bits shifted out on one side come back on the other. There's noRotateRight; pass a negative count instead.bits.UintSizeis 32 or 64, the size ofuintandinton the current platform.
math/bits also has Add64, Sub64, Mul64 and Div64, which return a carry, a borrow or the high half of the result. They are building blocks for arithmetic on numbers wider than 64 bits. See Operators for an example of detecting overflow with bits.Add64.
Iterating over set bits
Combining TrailingZeros with x &= x - 1 visits each set bit exactly once. The loop runs once per set bit, not once per bit of the type:
package main
import (
"fmt"
"math/bits"
)
// setBits returns positions of all set bits, lowest first
func setBits(x uint64) []int {
var res []int
for x != 0 {
i := bits.TrailingZeros64(x)
res = append(res, i)
x &= x - 1 // clear the lowest set bit
}
return res
}
func main() {
fmt.Println(setBits(0b1011_0010))
fmt.Println(setBits(1<<63 | 1))
fmt.Println(setBits(0))
}
[1 4 5 7]
[0 63]
[]
A bit set
A bit set stores a set of small non-negative integers using one bit per possible element. Membership test, insertion and removal are a single bitwise operation, and intersection or union processes 64 elements at a time:
package main
import (
"fmt"
"iter"
"math/bits"
)
// BitSet is a set of non-negative integers
type BitSet struct {
words []uint64
}
func (s *BitSet) Add(i int) {
w := i / 64
if w >= len(s.words) {
s.words = append(s.words, make([]uint64, w-len(s.words)+1)...)
}
s.words[w] |= 1 << (i % 64)
}
func (s *BitSet) Remove(i int) {
if w := i / 64; w < len(s.words) {
s.words[w] &^= 1 << (i % 64)
}
}
func (s *BitSet) Has(i int) bool {
w := i / 64
return w < len(s.words) && s.words[w]&(1<<(i%64)) != 0
}
func (s *BitSet) Len() int {
n := 0
for _, w := range s.words {
n += bits.OnesCount64(w)
}
return n
}
// All iterates over elements in increasing order
func (s *BitSet) All() iter.Seq[int] {
return func(yield func(int) bool) {
for wi, w := range s.words {
for w != 0 {
i := wi*64 + bits.TrailingZeros64(w)
if !yield(i) {
return
}
w &= w - 1
}
}
}
}
// Intersect keeps only elements that are also in other
func (s *BitSet) Intersect(other *BitSet) {
for i := range s.words {
if i < len(other.words) {
s.words[i] &= other.words[i]
} else {
s.words[i] = 0
}
}
}
func main() {
var a, b BitSet
for _, i := range []int{1, 3, 64, 100, 200} {
a.Add(i)
}
for _, i := range []int{3, 4, 100, 201} {
b.Add(i)
}
fmt.Println(a.Has(64), a.Has(65), a.Len())
for i := range a.All() {
fmt.Print(i, " ")
}
fmt.Println()
a.Remove(1)
a.Intersect(&b)
for i := range a.All() {
fmt.Print(i, " ")
}
fmt.Println()
}
true false 5
1 3 64 100 200
3 100
- element
ilives in wordi / 64, at biti % 64. Becauseiis anint, the compiler can't turn/and%into plain shifts unless it can provei >= 0. If it matters, useuintfor indexes. Allreturns aniter.Seq[int], so a set can be used directly in afor rangeloop (Go 1.23+).- union is
|=and difference is&^=on each word, written the same way asIntersect.
A []bool uses a byte per element. A bit set is 8 times smaller and much faster for set operations. For a production-ready implementation see github.com/bits-and-blooms/bitset.
Flags with a String method
When bit flags are part of an API, give the type a String method so that values print in a readable way. x &= x - 1 together with TrailingZeros makes it easy to visit each set flag:
package main
import (
"fmt"
"math/bits"
"strings"
)
type Style uint8
const (
Bold Style = 1 << iota
Italic
Underline
Strike
)
var styleNames = []string{"Bold", "Italic", "Underline", "Strike"}
func (s Style) Has(f Style) bool { return s&f == f }
func (s Style) String() string {
if s == 0 {
return "0"
}
var parts []string
for x := s; x != 0; x &= x - 1 {
i := bits.TrailingZeros8(uint8(x))
if i < len(styleNames) {
parts = append(parts, styleNames[i])
} else {
parts = append(parts, fmt.Sprintf("1<<%d", i))
}
}
return strings.Join(parts, "|")
}
func main() {
s := Bold | Underline
fmt.Println(s)
fmt.Println(s.Has(Bold), s.Has(Italic), s.Has(Bold|Underline), s.Has(Bold|Italic))
s |= Italic
s &^= Bold
fmt.Println(s, uint8(s))
fmt.Println(Style(0), Style(0b1001_0001))
}
Bold|Underline
true false true false
Italic|Underline 6
0 Bold|1<<4|1<<7
s.Has(Bold | Italic) checks that all given flags are set: s&f == f. To check whether any of them is set, use s&f != 0.
The String method also prints unknown bits instead of silently dropping them, which helps when debugging values that come from outside the program.
Signed integers
Go integers use two's complement representation. Converting between signed and unsigned types of the same size keeps the bits and only changes how they are interpreted:
package main
import "fmt"
// signExtend interprets the low n bits of x as a signed n-bit number
func signExtend(x uint32, n uint) int32 {
shift := 32 - n
return int32(x<<shift) >> shift
}
func main() {
var a int8 = -6
fmt.Printf("%08b\n", uint8(a)) // two's complement bits
fmt.Printf("%b\n", a) // %b on signed prints sign and magnitude
fmt.Println(a>>1, uint8(a)>>1) // arithmetic vs logical shift
fmt.Println(^a, -a) // ^a == -a - 1
// a 12-bit signed value, e.g. from a sensor register
fmt.Println(signExtend(0xFFF, 12), signExtend(0x800, 12), signExtend(0x7FF, 12))
// shifting by the type width or more gives 0 (or -1), not undefined behavior
var s uint = 40
var u uint32 = 0xFFFFFFFF
var i int32 = -1
fmt.Println(u<<s, u>>s, i>>s)
}
11111010
-110
-3 125
5 6
-1 -2048 2047
0 0 -1
%bon a signed value prints a minus sign and the magnitude, not the bits in memory. To see the actual bits, convert to the unsigned type of the same size first:uint8(a).>>on a signed integer is an arithmetic shift: it copies the sign bit, so-6 >> 1is-3. On an unsigned integer it's a logical shift that fills with zeros.^ais-a - 1for signed integers.signExtendturns an n-bit two's complement value (common in sensor registers and binary formats) into a Goint32: shift the field to the top of the word, then arithmetic-shift it back down so that the sign bit is copied.- shifting by the width of the type or more is well defined in Go: the result is
0, or-1when a negative signed value is shifted right. In C this is undefined behavior.
The shift count must not be negative. A negative shift count in a variable panics at run time with negative shift amount.
Byte order: encoding/binary
Multi-byte integers in files and network protocols are stored either big endian (most significant byte first, "network byte order") or little endian (least significant byte first, the native order of x86 and most ARM CPUs). Package encoding/binary converts between bytes and integers:
package main
import (
"encoding/binary"
"fmt"
)
func main() {
buf := []byte{0x12, 0x34, 0x56, 0x78}
fmt.Printf("%#x\n", binary.BigEndian.Uint32(buf))
fmt.Printf("%#x\n", binary.LittleEndian.Uint32(buf))
fmt.Printf("%#x\n", binary.BigEndian.Uint16(buf[2:]))
// the same thing by hand
v := uint32(buf[0])<<24 | uint32(buf[1])<<16 | uint32(buf[2])<<8 | uint32(buf[3])
fmt.Printf("%#x\n", v)
out := make([]byte, 4)
binary.LittleEndian.PutUint32(out, 0xCAFEBABE)
fmt.Printf("% x\n", out)
// Append* functions grow a slice
var msg []byte
msg = binary.BigEndian.AppendUint16(msg, 0xABCD)
msg = binary.BigEndian.AppendUint32(msg, 1)
msg = append(msg, 'h', 'i')
fmt.Printf("% x\n", msg)
// variable-length encoding: small numbers take fewer bytes
for _, n := range []uint64{1, 127, 128, 300, 1 << 40} {
b := binary.AppendUvarint(nil, n)
back, size := binary.Uvarint(b)
fmt.Printf("%d -> % x (decoded %d from %d bytes)\n", n, b, back, size)
}
}
0x12345678
0x78563412
0x5678
0x12345678
be ba fe ca
ab cd 00 00 00 01 68 69
1 -> 01 (decoded 1 from 1 bytes)
127 -> 7f (decoded 127 from 1 bytes)
128 -> 80 01 (decoded 128 from 2 bytes)
300 -> ac 02 (decoded 300 from 2 bytes)
1099511627776 -> 80 80 80 80 80 20 (decoded 1099511627776 from 6 bytes)
binary.BigEndianandbinary.LittleEndianhaveUint16,Uint32,Uint64for reading andPutUint16,PutUint32,PutUint64for writing into an existing slice. They panic if the slice is too short.AppendUint16,AppendUint32andAppendUint64(Go 1.19+) append to a slice, which is convenient for building messages.binary.NativeEndian(Go 1.21+) uses the byte order of the current CPU. Use it only for data that never leaves the machine.AppendUvarintandUvarintuse a variable-length encoding: 7 bits per byte, with the high bit meaning "more bytes follow", so small numbers take 1 byte. Protocol Buffers use the same encoding. For signed numbers useAppendVarintandVarint, which use zig-zag encoding so that small negative numbers are short too.
The hand-written version with shifts and ORs is what binary.BigEndian.Uint32 does internally. The compiler recognizes this pattern and turns it into a single load, plus a byte swap instruction if needed.
To get the raw IEEE 754 bits of a floating-point number, use math.Float64bits and math.Float64frombits, described in Math.
Common mistakes
Precedence of bitwise operators in Go differs from C, Java and JavaScript:
package main
import "fmt"
func main() {
const flag = 0b0100
x := 0b0110
// & binds tighter than == in Go (unlike C), so this is (x & flag) != 0
if x&flag != 0 {
fmt.Println("flag set")
}
// << binds tighter than +, so this is 1 + (2 << 3)
fmt.Println(1 + 2<<3)
// ^ is XOR, not exponentiation
fmt.Println(2^3, 1<<3)
var b byte = 0xF0
fmt.Printf("%08b %08b\n", ^b, b^0xFF) // unary ^ is NOT
}
flag set
17
1 8
00001111 00001111
&,<<and>>have the same precedence as*.x&flag != 0means(x & flag) != 0, which is what you want; in C it would meanx & (flag != 0). But1 + 2<<3is17in Go and24in C. When porting bit manipulation code, add parentheses.^is XOR, not exponentiation:2^3is1. Use1 << nfor powers of two andmath.Powfor floating-point powers.- there's no
~operator for integers. Bitwise NOT is unary^. - shifting a value whose type is too small:
uint32(b << 24)withbof typebyteis0. Convert first:uint32(b) << 24. - constant overflow is a compile error:
var b uint8 = 1 << 8fails withcannot use 1 << 8 (untyped int constant 256) as uint8 value in variable declaration (overflows). Shifts of variables silently drop the bits instead. intanduintare 32 bits on 32-bit platforms. When a bit layout matters (file formats, protocols, hashing), use sized types likeuint32anduint64.x % m == x & (m-1)is only true for non-negativex. For negativex, Go's%returns a negative remainder.
Summary
- use unsigned types for bit manipulation; write constants as
0bliterals and print them with%08b - set a bit with
x |= 1<<n, clear withx &^= 1<<n, toggle withx ^= 1<<n, test withx&(1<<n) != 0 - extract a field with
(x >> shift) & mask, wheremaskis1<<width - 1 x & (x-1)clears the lowest set bit;x & -xisolates itmath/bitsprovidesOnesCount,LeadingZeros,TrailingZeros,Len,ReverseandRotateLeft, all fast intrinsics- a bit set (
[]uint64) is a compact and fast set of small integers encoding/binaryreads and writes integers in big or little endian byte order- in Go
&and<<bind tighter than+and==, unlike in C