mirror of https://github.com/siddontang/go.git
hack add int to slice
This commit is contained in:
parent
0792eb6e26
commit
f02308217f
16
hack/hack.go
16
hack/hack.go
|
@ -25,3 +25,19 @@ func Slice(s string) (b []byte) {
|
|||
pbytes.Cap = pstring.Len
|
||||
return
|
||||
}
|
||||
|
||||
func Int64Slice(v int64) (b []byte) {
|
||||
pbytes := (*reflect.SliceHeader)(unsafe.Pointer(&b))
|
||||
pbytes.Data = uintptr(unsafe.Pointer(&v))
|
||||
pbytes.Len = 8
|
||||
pbytes.Cap = 8
|
||||
return
|
||||
}
|
||||
|
||||
func Int32Slice(v int32) (b []byte) {
|
||||
pbytes := (*reflect.SliceHeader)(unsafe.Pointer(&b))
|
||||
pbytes.Data = uintptr(unsafe.Pointer(&v))
|
||||
pbytes.Len = 4
|
||||
pbytes.Cap = 4
|
||||
return
|
||||
}
|
||||
|
|
|
@ -2,6 +2,7 @@ package hack
|
|||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"testing"
|
||||
)
|
||||
|
||||
|
@ -34,3 +35,21 @@ func TestByte(t *testing.T) {
|
|||
t.Fatal(string(b))
|
||||
}
|
||||
}
|
||||
|
||||
func TestInt(t *testing.T) {
|
||||
if int64(binary.LittleEndian.Uint64(IntSlice(1))) != 1 {
|
||||
t.Fatal("error")
|
||||
}
|
||||
|
||||
if int64(binary.LittleEndian.Uint64(IntSlice(-1))) != -1 {
|
||||
t.Fatal("error")
|
||||
}
|
||||
|
||||
if int64(binary.LittleEndian.Uint64(IntSlice(32768))) != 32768 {
|
||||
t.Fatal(1)
|
||||
}
|
||||
|
||||
if int64(binary.LittleEndian.Uint64(IntSlice(-32768))) != -32768 {
|
||||
t.Fatal(1)
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue