转换之前,我们先了解string与byte的底层结构
string
type StringHeader struct {
Data uintptr
Len int
}
slice
type SliceHeader struct {
Data uintptr
Len int
Cap int
}
利用unsafe.Pointer进行类型转换,完成数据展示,因为slice与string底部数据存储方式都是uintptr以byte形式
string转byte
func stringTobytes(s string) []byte {
str := (*reflect.StringHeader)(unsafe.Pointer(&s))
by := reflect.SliceHeader{
Data: str.Data,
Len: str.Len,
Cap: str.Len,
}
//在把by从sliceheader转为[]byte类型
return *(*[]byte)(unsafe.Pointer(&by))
}
byte转string
func byteToString(b []byte) string {
by := (*reflect.SliceHeader)(unsafe.Pointer(&b))
str := reflect.StringHeader{
Data: by.Data,
Len: by.Len,
}
return *(*string)(unsafe.Pointer(&str))
}