How to Convert []uint8 to string

Viewed 1978

I am observing the log of a program in the Go, and in the output I see this:

[]uint8=[18 32 96 38 15 212 226 233 58 14 183 212 80 4 175 97 28 235 76 154 244 210 200 18 131 241 31 86 179 109 228 190 78 72])

Now I would like to be able to convert this to a form where I can see what it means. This should be string content represented as []uint8.

But when I call the string method on that value as suggested in this link here I get a gibberish output.

Go Playground link here

What could I be doing wrong and how to go about this conversion?

2 Answers

The conversion s := string(stuff) is fine, but usually you'd expect stuff to contain actual printable character sequences. In your case, it doesn't (mostly).

Make sure to read Strings, bytes, runes and characters in Go in detail.


Modifying your example to print byte values that have ASCII letter mappings:

package main

import (
    "fmt"
)

func main() {
    stuff := []byte{97, 98, 99, 100}
    s := string(stuff)
    fmt.Println(s)
}

Prints "abcd".

Actually your code is ok which you mention in GO Playground & there is nothing wrong.

And []byte{18, 32, 112, 236, 92, 145, 161, 6, 131, 219, 133, 202, 254, 245, 176, 35, 42, 161, 94, 140, 190, 7, 216, 132, 6, 225, 132, 162, 24, 48, 197, 33, 11, 111} here some element are not able to print the character. So I think you should get idea of ASCII Table. Then you will never confused about output.

visit on this https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html to get the idea of ASCII Table

Related