1
0
mirror of https://github.com/charlienet/go-mixed.git synced 2025-07-18 00:22:41 +08:00

字节数组与整数转换

This commit is contained in:
2022-03-27 10:19:12 +08:00
parent 59ea343843
commit 176cd0575d
2 changed files with 62 additions and 0 deletions

View File

@ -0,0 +1,8 @@
package bytesconv
import "testing"
func TestBytesToUint64(t *testing.T) {
t.Log(BigEndian.BytesToUInt64([]byte{0x88, 0x45}))
t.Log(LittleEndian.BytesToUInt64([]byte{0x88, 0x45}))
}

54
bytesconv/bytesconv.go Normal file
View File

@ -0,0 +1,54 @@
package bytesconv
import (
"fmt"
"unsafe"
)
// StringToBytes converts string to byte slice without a memory allocation.
func StringToBytes(s string) (b []byte) {
return *(*[]byte)(unsafe.Pointer(
&struct {
string
Cap int
}{s, len(s)},
))
}
// BytesToString converts byte slice to string without a memory allocation.
func BytesToString(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
}
type endian int
const (
BigEndian endian = iota + 1
LittleEndian
)
func (e endian) BytesToUInt64(data []byte) (uint64, error) {
if len(data) > 8 {
return 0, fmt.Errorf("bytes to uint64, bytes length is invaild")
}
var ret uint64
var len int = len(data)
if e == BigEndian {
for i := 0; i < len; i++ {
ret = ret | (uint64(data[len-1-i]) << (i * 8))
}
} else {
for i := 0; i < len; i++ {
ret = ret | (uint64(data[i]) << (i * 8))
}
}
return ret, nil
}
func BytesToUInt64Big() {
// binary.BigEndian
// binary.LittleEndian
}