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 create thumbnail of an image?
Runtime package variables
Normal function parameter with variadic function parameter
How to iterate over a Map using for loop in Go?
Converting Int data type to Float in Go
Golang HTTP GET request with parameters
Regular expression to validate common Credit Card Numbers
Example of Switch Case with Break in For Loop
How to convert Boolean Type to String in Go?
Add N number of Year, Month, Day, Hour, Minute, Second, Millisecond, Microsecond and Nanosecond to current date-time