Golang笔记

Golang byte to string 的方法实践

Golang byte to string 的方法实践

通常使用的方式

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

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))
}
本文网址: https://golangnote.com/topic/186.html (转载注明出处)
关于GolangNote:记录在工作中使用golang 遇到、面临的相关问题及解决方法。如果你在这里获得一些知识或信息,解决你的编程问题,请考虑捐赠给不幸的人或者你喜欢的慈善机构,除捐赠外,种植树木、志愿服务或减少排碳的行为也很有益处。如果你有任何问题可以在下面 留言
Be the first to comment!
Captcha image
Relative Articles