### 源码:
```go
root@jack-VirtualBox:~/test/zz# cat main.go
package main
import (
"errors"
"fmt"
"reflect"
)
func reserveint1(d interface{}) interface{} {
flagint := false
h := 0
dsd := reflect.ValueOf(d)
switch reflect.TypeOf(d) {
case reflect.TypeOf(int(0)):
h = 8
flagint = true
case reflect.TypeOf(int8(0)):
h = 8
flagint = true
case reflect.TypeOf(int16(0)):
h = 16
flagint = true
case reflect.TypeOf(int32(0)):
h = 32
flagint = true
case reflect.TypeOf(int64(0)):
h = 64
flagint = true
case reflect.TypeOf(uint(0)):
h = 8
case reflect.TypeOf(uint8(0)):
h = 8
case reflect.TypeOf(uint16(0)):
h = 16
case reflect.TypeOf(uint32(0)):
h = 32
case reflect.TypeOf(uint64(0)):
h = 64
default:
return errors.New("not int type")
}
if flagint {
ds := dsd.Int()
var dd int64
for i := 0; ds != 0; i++ {
if (ds & 0x01) != 0 {
dd |= 1 << (h - 1 - i)
}
ds = ds >> 1
}
return dd
} else {
ds := dsd.Uint()
var dd uint64
for i := 0; ds != 0; i++ {
if (ds & 0x01) != 0 {
dd |= 1 << (h - i)
}
ds = ds >> 1
}
return dd
}
}
func reserveint(d int64) int64 {
var dd int64
for i := 0; d != int64(0); i++ {
if (d & 0x01) != int64(0) {
dd |= 1 << (63 - i)
}
d = d >> 1
}
return dd
}
func main() {
fmt.Println("实现位反转")
d := int64(0xaa12)
fmt.Printf("%064b\r\n", d)
dd := reserveint(d)
fmt.Printf("%064b\r\n", dd)
fmt.Println("\r\n用反射实现位反转, 64 bit")
dt := int64(0xaa12)
fmt.Printf("dt is:%064b\r\n", dt)
dy := reserveint1(dt)
fmt.Printf("dy is:%064b\r\n", dy)
fmt.Println("\r\n用反射实现位反转, 32 bit")
dz := int32(0xaa12)
fmt.Printf("dz is:%032b\r\n", dz)
dx := reserveint1(dz)
fmt.Printf("dx is:%032b\r\n", dx)
fmt.Println("\r\n用反射实现位反转, 16 bit")
dk := int16(0xa12)
fmt.Printf("dk is:%016b\r\n", dk)
dl := reserveint1(dk)
fmt.Printf("dl is:%016b\r\n", dl)
fmt.Println("\r\n用反射实现位反转, 8 bit")
dm := int8(0x12)
fmt.Printf("dm is:%08b\r\n", dm)
dn := reserveint1(dm)
fmt.Printf("dn is:%08b\r\n", dn)
}
root@jack-VirtualBox:~/test/zz#
```
### 执行:
```go
root@jack-VirtualBox:~/test/zz# go run main.go
实现位反转
0000000000000000000000000000000000000000000000001010101000010010
0100100001010101000000000000000000000000000000000000000000000000
用反射实现位反转, 64 bit
dt is:0000000000000000000000000000000000000000000000001010101000010010
dy is:0100100001010101000000000000000000000000000000000000000000000000
用反射实现位反转, 32 bit
dz is:00000000000000001010101000010010
dx is:01001000010101010000000000000000
用反射实现位反转, 16 bit
dk is:0000101000010010
dl is:0100100001010000
用反射实现位反转, 8 bit
dm is:00010010
dn is:01001000
root@jack-VirtualBox:~/test/zz#
```
有疑问加站长微信联系(非本文作者))