Is there a function calc log2 of an integer in go?

346 views
Skip to first unread message

shiwei xu

unread,
Jan 2, 2012, 7:46:33 AM1/2/12
to golang-nuts
In x86, there is an instruction named bsr doing this:

int log2(int x) {
    asm bsr eax, x
}

Jan Mercl

unread,
Jan 2, 2012, 8:03:43 AM1/2/12
to golan...@googlegroups.com
E.g. some of these C log2 techniques (http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious) could be probably easily rewritten in Go.

minux

unread,
Jan 2, 2012, 8:47:30 AM1/2/12
to shiwei xu, golang-nuts
I guess you are writing performance critical code? If it's so, you can always easily
define assembly function like this yourself.

As an example, I created a mymath.Log2 to use BSR on amd64.

First, you need to create a mymath.go file to declare the package interface:
package mymath
func Log2(uint64) uint64

then the assembler implementation, log2_amd64.s, as per Go's naming convention:
TEXT ·Log2(SB),7,$0 // NOTE the · before the actual name, no pkg name here
        BSRQ 8(SP), AX // 8(SP) is the first argument
        MOVQ AX, 16(SP) // store result
        RET

Finally, a simple test file log2.go (not a test case, so it won't use the testing pkg):
package main
import "mymath"
func test(x uint64) {
        println(x, " = ", mymath.Log2(x))
}
func main() {
        test(0)
        test(1)
        test(4)
        test(10)
        test(17)
        test(1<<37)
        test(1<<37-2)
}

now, let's run it:
6a log2_amd64.s
6g mymath.go
gopack grc mymath.a mymath.6 log2_amd64.6
6g -I . log2.go
6l -L . log2.6
./6.out

Result:
0  =  1
1  =  0
4  =  2
10  =  3
17  =  4
137438953472  =  37
137438953470  =  36


Reply all
Reply to author
Forward
0 new messages