如何反转二进制数?

I'm newbie in Golan, this should be an easy question for experienced golang devs. I try to do the same test from Spotify to see how fast we can go in Golang :)

The usual bit-twiddling C solutions translate immediately to Go.

package main

import "fmt"

func BitReverse32(x uint32) uint32 {
    x = (x&0x55555555)<<1 | (x&0xAAAAAAAA)>>1
    x = (x&0x33333333)<<2 | (x&0xCCCCCCCC)>>2
    x = (x&0x0F0F0F0F)<<4 | (x&0xF0F0F0F0)>>4
    x = (x&0x00FF00FF)<<8 | (x&0xFF00FF00)>>8
    return (x&0x0000FFFF)<<16 | (x&0xFFFF0000)>>16
}

func main() {
    cases := []uint32{0x1, 0x100, 0x1000, 0x1000000, 0x10000000, 0x80000000, 0x89abcdef}
    for _, c := range cases {
        fmt.Printf("%08x -> %08x
", c, BitReverse32(c))
    }
}

The most straight-forward solution would be converting the bits into a number with strconv and then reversing the number by shifting the bits. I'm not sure how fast it would be, but it should work.

package main

import "fmt"
import "strconv"

func main() {
    bits := "10100001"
    bits_number := 8
    number, _ := strconv.ParseUint(bits, 2, bits_number)
    r_number := number - number // reserve type
    for i := 0; i < bits_number; i++ {
        r_number <<= 1
        r_number |= number & 1
        number >>= 1
    }
    fmt.Printf("%s [%d]
", strconv.FormatUint(r_number, 2), r_number)
}

http://play.golang.org/p/YLS5wkY-iv

Note: since 2013, you now have a dedicate math/bits package with Go 1.9 (August 2017).

And it does come with a collection of Reverse() and ReverseBytes() functions: no need to implement one anymore.

Plus, on most architectures, functions in this package are additionally recognized by the compiler and treated as intrinsics for additional performance.