From 176cd0575df8964b0819bbb636b36324d78fccea Mon Sep 17 00:00:00 2001 From: charlie <3140647@qq.com> Date: Sun, 27 Mar 2022 10:19:12 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AD=97=E8=8A=82=E6=95=B0=E7=BB=84=E4=B8=8E?= =?UTF-8?q?=E6=95=B4=E6=95=B0=E8=BD=AC=E6=8D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bytesconv/byteconv_test.go | 8 ++++++ bytesconv/bytesconv.go | 54 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 bytesconv/byteconv_test.go create mode 100644 bytesconv/bytesconv.go diff --git a/bytesconv/byteconv_test.go b/bytesconv/byteconv_test.go new file mode 100644 index 0000000..bced062 --- /dev/null +++ b/bytesconv/byteconv_test.go @@ -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})) +} diff --git a/bytesconv/bytesconv.go b/bytesconv/bytesconv.go new file mode 100644 index 0000000..12c813c --- /dev/null +++ b/bytesconv/bytesconv.go @@ -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 +}