Go
4 min read
INTERMEDIATE
Calculate with math/bits
Quick Answermath/bits provides unsigned integer operations including counting set bits and arithmetic with carry. Fixed-width functions like OnesCount64 and Add64 specify the word size explicitly.
Calculate with math/bits
math/bits provides unsigned integer operations including counting set bits and arithmetic with carry. Fixed-width functions like OnesCount64 and Add64 specify the word size explicitly.
Try this programgo
package main
import ( "fmt" "math/bits")
func main() { mask := uint8(0b10110100) fmt.Println(bits.OnesCount8(mask))}Four bits are set. Population count counts ones, not the position of the most significant bit.
Expected output:
text
4Keep the carry bit
A useful variationgo
package main
import ( "fmt" "math" "math/bits")
func main() { sum, carry := bits.Add64(math.MaxUint64, 1, 0) fmt.Println(sum, carry) high, low := bits.Mul64(1<<63, 2) fmt.Println(high, low)}Add64 returns low 64 bits then carry. Its carry input must be zero or one. Mul64 instead returns high word then low word. Do not interchange the return orders.
Expected output:
text
0 11 0Try it locally
Count set bits in 0b11110001.
Assessments & Practice
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
+30 XP Available
Concept Quiz & Questions
Numeric engineering 04: Calculate with math/bits
Check the lesson objective before moving on.
+30 XP
Answered: 0 of 20%
1
What does bits.OnesCount8 count?
2
What does Add64 return after the sum?
Complete all questions to submit