Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert [Size]byte to string in Go?

I have a sized byte array that I got after doing md5.Sum().

data := []byte("testing")
var pass string 
var b [16]byte
b = md5.Sum(data)
pass = string(b)

I get the error:

cannot convert b (type [16]byte) to type string

like image 836
Thejus Krishna Avatar asked Sep 27 '14 08:09

Thejus Krishna


People also ask

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.

How many bytes is a Go?

Like byte type, Go has another integer type rune . It is aliases for int32 (4 bytes) data types and is equal to int32 in all ways.


3 Answers

You can refer to it as a slice:

pass = string(b[:])
like image 175
Simon Whitehead Avatar answered Sep 23 '22 00:09

Simon Whitehead


A little late but keep in mind that using string(b[:]) will print mostly invalid characters.

If you're trying to get a hex representation of it like php you can use something like:

data := []byte("testing")
b := md5.Sum(data)

//this is mostly invalid characters
fmt.Println(string(b[:]))

pass := hex.EncodeToString(b[:])
fmt.Println(pass)
// or
pass = fmt.Sprintf("%x", b)
fmt.Println(pass)

playground

like image 49
OneOfOne Avatar answered Sep 21 '22 00:09

OneOfOne


it can be solved by this

pass = fmt.Sprintf("%x", b)

or

import "encoding/base64"
pass = base64.StdEncoding.EncodeToString(b[:])

this will encoding it to base64 string

like image 14
chuixue Avatar answered Sep 19 '22 00:09

chuixue