Different ways to convert Byte Array into String
Below are 3 examples to convert Byte Array into String. All example will display output.
Example
package main
import (
"fmt"
"reflect"
"unsafe"
"bytes"
)
func BytesToString(b []byte) string {
bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
sh := reflect.StringHeader{bh.Data, bh.Len}
return *(*string)(unsafe.Pointer(&sh))
}
func main() {
/***************************************/
byteArray1 := []byte{'J', 'O', 'H', 'N'}
str1 := BytesToString(byteArray1)
fmt.Println("String:",str1)
/****************************************/
str2 := string(byteArray1[:])
fmt.Println("String:",str2)
/****************************************/
str3 := bytes.NewBuffer(byteArray1).String()
fmt.Println("String:",str3)
}
Most Helpful This Week
Find element in a slice and move it to first position?
How to check if a string contains a numbers in Golang?
How to import and alias package names?
Encoding and Decoding using json.Marshal and json.Unmarshal
How pointer & and * and ** works in Golang?
How to get struct variable information using reflect package?