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 array in Go Programming Language?
Golang HTML parser
How to Convert string to integer type in Go?
Normal function parameter with variadic function parameter
How to concatenate two or more slices in Golang?
Find length of Channel, Pointer, Slice, String and Map
Example to compare Println vs Printf
How to blur an image in Golang?
How to play and pause execution of goroutine?
Example of Fscan, Fscanf, and Fscanln from FMT Package