简体   繁体   中英

Convert a byte to a string in Go

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[:])

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[:])

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 .

类似于 inf 的建议,但允许使用逗号:

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

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

func convert( b []byte ) string {
    s := make([]string,len(b))
    for i := range b {
        s[i] = string(b[i])
    }
    return strings.Join(s,",")
}

hex.EncodeToString(input)可能适合你。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM