Golang byte to string 的方法实践
通常使用的方式
使用标准库提供的方式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package main
import (
"bytes"
"fmt"
)
func main() {
byteArray := []byte("hello encoding/binary")
fmt.Println(byteArray)
byteCode := 'i'
fmt.Println(byteCode)
//n := bytes.Index(byteArray, []byte{105})
n := bytes.IndexByte(byteArray, 105)
fmt.Println(n)
s := string(byteArray[:n])
fmt.Println(s)
//s := string(byteArray[:])
}
使用 unsafe
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package main
import (
"fmt"
"reflect"
"unsafe"
)
func BytesToString(b []byte) string {
bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
sh := reflect.StringHeader{bh.Data, bh.Len}
return *(*string)(unsafe.Pointer(&sh))
}
func StringToBytes(s string) []byte {
sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
bh := reflect.SliceHeader{sh.Data, sh.Len, 0}
return *(*[]byte)(unsafe.Pointer(&bh))
}
func main() {
b := []byte{'b', 'y', 't', 'e'}
s := BytesToString(b)
fmt.Println(s)
b = StringToBytes(s)
fmt.Println(string(b))
}
// ByteSliceToString is used when you really want to convert a slice // of bytes to a string without incurring overhead. It is only safe
// to use if you really know the byte slice is not going to change // in the lifetime of the string
func ByteSliceToString(bs []byte) string {
// This is copied from runtime. It relies on the string
// header being a prefix of the slice header!
return *(*string)(unsafe.Pointer(&bs))
}
unsafe 方式性能超赞,但顾名思义 unsafe
,至少目前用了10年没问题,如果 go 有重大变化。
本文网址: https://golangnote.com/topic/186.html 转摘请注明来源