Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert byte array to string in Go [duplicate]

Tags:

types

go

sha1

[]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!

like image 323
lindsay show Avatar asked Nov 16 '16 12:11

lindsay show


3 Answers

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

myString := string(myBytes[:])
like image 165
warbear0129 Avatar answered Oct 13 '22 20:10

warbear0129


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)
like image 72
rustyx Avatar answered Oct 13 '22 18:10

rustyx


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.

like image 12
Franck Jeannin Avatar answered Oct 13 '22 19:10

Franck Jeannin