Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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[:])
like image 305
ZHAO Xudong Avatar asked Jul 04 '15 12:07

ZHAO Xudong


People also ask

Can we convert byte to string?

Given a bytes object, you can use the built-in decode() method to convert the byte to a string. You can also pass the encoding type to this function as an argument. For example, let's use the UTF-8 encoding for converting bytes to a string: byte_string = b"Do you want a slice of \xf0\x9f\x8d\x95?"

What is a byte string in GoLang?

A byte refers to an 8-bit unsigned integer. Bytes are very common when working with slices. In go, we can convert a string to a byte using the byte() function. The function syntax is as shown: []byte(string)

What is byte array in Go?

A byte in Go is an unsigned 8-bit integer. It has type uint8 . A byte has a limit of 0 – 255 in numerical range. It can represent an ASCII character.


2 Answers

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

like image 143
Sathish Avatar answered Oct 08 '22 14:10

Sathish


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[:])
like image 29
Didier Spezia Avatar answered Oct 08 '22 13:10

Didier Spezia