0

I am trying to convert a single byte value to a string in golang. When I do a typecast of a byte to string like string(byte) and print the value I get "{" in response. I read other answers that the correct way to convert a byte to string would be strconv.Itoa(int(bytevalue)). Why does the former not work and why is the latter approach correct.

1 Answer 1

2

The expression string(bytevalue) is a conversion, not a typecast. The specification says this about conversions from numeric types to a string:

Converting a signed or unsigned integer value to a string type yields a string containing the UTF-8 representation of the integer.

The expression string(byte(123)) evaluates to the string "{" because { is the the string containing the UTF-8 representation of the rune 123.

Use the strconv package to get the decimal representation of the byte. The expression strconv.Itoa(int(byte(123))) evaluates to the string "123".

Sign up to request clarification or add additional context in comments.

Comments

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.