Python bytes() or bytesarray() counterpart in golang

Issue

I am looking to port some code from python into golang.
The code in python goes like this

to_be_converted = [3, 40, 234, 1, 23, 65, 43, 72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]
converted = bytes(to_be_converted)
print(converted)

this results to

b'\x03(\xea\x01\x17A+Hello world'

I am looking for a way to get this bytes object in golang.
I dont mind if the input data is different, I am only looking for a way to obtain the output.
Thank you

Solution

Go has a builtin byte type and you can create byte arrays like this:

myBytes := []byte{3, 40, 234, 1, 23, 65, 43, 72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100}

To get the string output, you can just convert the byte array to a string like this:

myString := string(myBytes)
fmt.Println(myString)// prints (´┐ŻA+Hello world

Answered By – smorrin

Answer Checked By – Terry (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.