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

3
  • Have you checked this? stackoverflow.com/a/28261008/5927361 Commented Feb 16, 2022 at 13:26
  • 1
    Does this help? stackoverflow.com/questions/40632802/… Commented Feb 16, 2022 at 13:27
  • Do you specifically want the exact string b'\x03(\xea\x01\x17A+Hello world'? If so, you should clarify this. Commented Feb 16, 2022 at 13:39

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.