35 lines
712 B
Go
35 lines
712 B
Go
package utils
|
|
|
|
import (
|
|
"encoding/binary"
|
|
"unsafe"
|
|
)
|
|
|
|
func Int2binary(num int, b int) []byte {
|
|
var a int64 //Go的破毛病
|
|
buf := make([]byte, unsafe.Sizeof(a))
|
|
if len(buf) > b {
|
|
panic("int2binary: buff must be greater than size of int64")
|
|
}
|
|
binary.PutVarint(buf, int64(num))
|
|
ret := make([]byte, b)
|
|
for i := 0; i < len(ret); i++ {
|
|
ret[i] = 0
|
|
}
|
|
copy(ret, buf)
|
|
return ret
|
|
}
|
|
|
|
func Binary2Int(bin []byte) int {
|
|
var a int64 //Go的破毛病
|
|
b := unsafe.Sizeof(a) //只取前面几位
|
|
num, n := binary.Varint(bin[:b])
|
|
if n == 0 {
|
|
panic("Binary2Int:buf too small")
|
|
}
|
|
if n < 0 {
|
|
panic("value larger than 64 bits (overflow) sand -n is the number of bytes read")
|
|
}
|
|
return int(num)
|
|
}
|