When I learning the golang tour and do the Stringer practice, I want to join the []byte
element to a string. Here are the examples.
Examples
Below are 3 examples to convert Byte Array into String. All example will display output.
package main
import (
"bytes"
"fmt"
"reflect"
"unsafe"
)
func BytesToString(b []byte) string {
bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
sh := reflect.StringHeader{Data: bh.Data, Len: bh.Len}
return *(*string)(unsafe.Pointer(&sh))
}
func main() {
byteArray0 := string([]byte{86, 90, 72, 73, 77, 65})
fmt.Println("String:", byteArray0)
byteArray1 := []byte{'V', 'Z', 'H', 'I', 'M', 'A'}
str1 := BytesToString(byteArray1)
fmt.Println("String:", str1)
str2 := string(byteArray1[:])
fmt.Println("String:", str2)
str3 := bytes.NewBuffer(byteArray1).String()
fmt.Println("String:", str3)
}
Output:
String: VZHIMA
String: VZHIMA
String: VZHIMA
String: VZHIMA
Program exited.
For IPAddr Practice
package main
import (
"fmt"
"strconv"
"strings"
)
func main() {
bytes := [4]byte{1, 2, 3, 4}
str := convert(bytes[:])
fmt.Printf(str)
}
func convert(b []byte) string {
s := make([]string, len(b))
for i := range b {
s[i] = strconv.Itoa(int(b[i]))
}
return strings.Join(s, ".")
}
Output:
1.2.3.4
Program exited.
FYI: