How to convert 127 (byte type) to "127" (string type) in Go?

Hello fellow gophers!

I’m going through the Go tour and I’m having trouble with a certain exercise.

At the interface tutorial we are supposed to add support to a type for the Stringer interface. The type is an array of byte (var IPAddr [4]byte).

I define correctly the method with the appropriate value receiver and in the body of the String function I range over the bytes in the receiver parameter and append them one by one to a byte slice I have created. After each byte I also insert byte(’.’) (the point of the exercise is to allow IPAddr to print eg {127, 1, 1, 0} as “”). Finally, I return a string() cast of the byte slice.

I know the code works but the output is not what I hoped it would be.

What seems to happen is that the bytes in the slice are converted into the character that corresponds to the byte value under the encoding used instead of the characters that correspond to the byte value digits.

Any pointers on how to deal with this would be greatly appreciated!

I’d like to see your code to see what you are doing. Here is my playground example:


Hint: package strconv.

1 Like

Hello Curtis,

here you Go :wink:

Hello Chris,

I did try using the Itoa function (from strconv) here.

Will try later to see if I can make it more elegant using eg a for loop.


Obviously any refinements/hints/suggestions are more than welcome!

So why not Sprintf from fmt?

Sure, Sprintf looks great!

Thanks Curtis.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.