1

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

Konik
  • 33
  • 3
  • Have you checked this? https://stackoverflow.com/a/28261008/5927361 – Kisinga Feb 16 '22 at 13:26
  • 1
    Does this help? https://stackoverflow.com/questions/40632802/how-to-convert-byte-array-to-string-in-go – Chris Feb 16 '22 at 13:27
  • Do you specifically want the exact string `b'\x03(\xea\x01\x17A+Hello world'`? If so, you should clarify this. – Zyl Feb 16 '22 at 13:39

1 Answers1

3

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
smorrin
  • 86
  • 2
  • 6
  • To get output closer to what the OP wanted, one would use the `%q` verb with `fmt.Printf`, which also accepts `[]byte` and does not require type-conversion to `string`. – kostix Feb 16 '22 at 13:59