GolangNote

Golang笔记

Golang byte to string 的方法实践

Permalink

Golang byte to string 的方法实践

通常使用的方式

使用标准库提供的方式

Go: byte 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

Go: 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 转摘请注明来源

Related articles

Golang Web 程序生产环境独立部署示例

一个 web 应用通常是跑在一个前端代理,如 Nginx 后,这样可以方便的在同一个服务器部署多个应用。这里说的独立部署是指让 go web 程序直接暴露在外面,独占 443、80 端口(俗称裸跑)。这样做除了性能有些提高外,更重要的是部署方便。...

Golang 泛型性能初识

编程时,我们通常需要编写“泛型”函数,其中确切的数据类型并不重要。例如,您可能想编写一个简单的函数来对数字进行求和。Go 直到最近才有这个概念,但最近才添加了它(从1.18版开始)。...

Write a Comment to "Golang byte to string 的方法实践"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.20 Processed in 0ms