Convert a byte to a string in Go

27,276

Solution 1

Not the most efficient way to implement it, but you can simply write:

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,",")
}

to be called by:

bytes := [4]byte{1,2,3,4}
str := convert(bytes[:])

Solution 2

If you are not bound to the exact representation then you can use fmt.Sprint:

fmt.Sprint(bytes) // [1 2 3 4]

On the other side if you want your exact comma style then you have to build it yourself using a loop together with strconv.Itoa.

Solution 3

Similar to inf's suggestion but allowing for commas:

fmt.Sprintf("%d,%d,%d,%d", bytes[0], bytes[1], bytes[2], bytes[3])

Solution 4

using strings.Builder would be the most efficient way to do the same..

package main

import (
  "fmt"
  "strings"
)

func convert( bytes []byte) string {
    var str strings.Builder
    for _, b := range bytes {
       fmt.Fprintf(&str, "%d,", int(b))
    }
    return str.String()[:str.Len() - 1]
}

func main(){
    s := [4]byte{1,2,3,4}
    fmt.Println(convert(s[:]))
}

=> 1,2,3,4

Share:
27,276
ZHAO Xudong
Author by

ZHAO Xudong

Web worker

Updated on July 09, 2022

Comments

  • ZHAO Xudong
    ZHAO Xudong almost 2 years

    I am trying to do something like this:

    bytes := [4]byte{1,2,3,4}
    str := convert(bytes)
    
    //str == "1,2,3,4"
    

    I searched a lot and really have no idea how to do this.

    I know this will not work:

    str = string(bytes[:])