hack add int to slice

This commit is contained in:
siddontang 2014-05-09 09:39:23 +08:00
parent 0792eb6e26
commit f02308217f
2 changed files with 35 additions and 0 deletions

View File

@ -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
}

View File

@ -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)
}
}