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
How to use function from another file golang?
Example: Arrays of Arrays, Arrays of Slices, Slices of Arrays and Slices of Slices
Strip all white spaces, tabs, newlines from a string
Golang Read Write and Process data in CSV
How to extract text from between html tag using Regular Expressions in Golang?
Get current date and time in various format in golang