How to convert byte array to string in Go

GoTypesSha1

Go Problem Overview


[]byte to string raises an error. string([]byte[:n]) raises an error too. By the way, for example, sha1 value to string for filename. Does it need utf-8 or any other encoding set explicitly? Thanks!

Go Solutions


Solution 1 - Go

The easiest method I use to convert byte to string is:

myString := string(myBytes[:])

Solution 2 - Go

The easiest way to convert []byte to string in Go:

myString := string(myBytes)

Note: to convert a "sha1 value to string" like you're asking, it needs to be encoded first, since a hash is binary. The traditional encoding for SHA hashes is hex (import "encoding/hex"):

myString := hex.EncodeToString(sha1bytes)

Solution 3 - Go

In Go you convert a byte array (utf-8) to a string by doing string(bytes) so in your example, it should be string(byte[:n]) assuming byte is a slice of bytes.

Solution 4 - Go

I am not sure that i understand question correctly, but may be:

var ab20 [20]byte = sha1.Sum([]byte("filename.txt"))
var sx16 string = fmt.Sprintf("%x", ab20)
fmt.Print(sx16)

https://play.golang.org/p/haChjjsH0-

Solution 5 - Go

ToBe := [6]byte{65, 66, 67, 226, 130, 172}
s:=ToBe[:3]
// this will work
fmt.Printf("%s",string(s))
// this will not
fmt.Printf("%s",string(ToBe))

Difference : ToBe is an array whereas s is a slice.

Solution 6 - Go

First you're getting all these negatives reviews because you didn't provided any code. Second, without a good example. This is what i'd do

var Buf bytes.Buffer
Buf.Write([]byte)
myString := Buf.String()
Buf.Reset() // Reset the buffer to reuse later

or better yet

myString := string(someByteArray[:n])

see here also see @JimB's comment

That being said if you help that targets your program, please provide and example of what you've tried, the expect results, and error.

Solution 7 - Go

We can just guess what is wrong with your code because no meaningful example is provided. But first what I see that string([]byte[:n]) is not valid at all. []byte[:n] is not a valid expression because no memory allocated for the array. Since byte array could be converted to string directly I assume that you have just a syntax error.

Shortest valid is fmt.Println(string([]byte{'g', 'o'}))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionlindsay showView Question on Stackoverflow
Solution 1 - Gowarbear0129View Answer on Stackoverflow
Solution 2 - GorustyxView Answer on Stackoverflow
Solution 3 - GoFranck JeanninView Answer on Stackoverflow
Solution 4 - GoalarclView Answer on Stackoverflow
Solution 5 - GoDev KalraView Answer on Stackoverflow
Solution 6 - GoreticentrootView Answer on Stackoverflow
Solution 7 - GoI159View Answer on Stackoverflow