ringbuffer的源码有一段看不太懂 求指教

// roundUp takes a uint64 greater than 0 and rounds it up to the next
// power of 2.
func roundUp(v uint64) uint64 {
    v--
    v |= v >> 1
    v |= v >> 2
    v |= v >> 4
    v |= v >> 8
    v |= v >> 16
    v |= v >> 32
    v++
    return v
}

共 2 个回复


x0601y

这是哪个Repo的ringbuffer?

# 0

heimeil

仔细观察

package main

import (
    "fmt"
)

func main() {
    var n uint64 = 100
    fmt.Println(roundUp(n))
}

func roundUp(v uint64) uint64 {
    fmt.Printf("v= %064b\n", v)
    v--
    fmt.Printf("-1 %064b\n", v)
    var tmp uint64
    tmp = v >> 1
    fmt.Printf(">> %064b\n", tmp)
    v |= tmp
    fmt.Printf("v| %064b\n", v)
    tmp = v >> 2
    fmt.Printf(">> %064b\n", tmp)
    v |= tmp
    fmt.Printf("v| %064b\n", v)
    tmp = v >> 4
    fmt.Printf(">> %064b\n", tmp)
    v |= tmp
    fmt.Printf("v| %064b\n", v)
    tmp = v >> 8
    fmt.Printf(">> %064b\n", tmp)
    v |= tmp
    fmt.Printf("v| %064b\n", v)
    tmp = v >> 16
    fmt.Printf(">> %064b\n", tmp)
    v |= tmp
    fmt.Printf("v| %064b\n", v)
    tmp = v >> 32
    fmt.Printf(">> %064b\n", tmp)
    v |= tmp
    fmt.Printf("v| %064b\n", v)
    v++
    fmt.Printf("+1 %064b\n", v)
    return v
}
# 1