In the following method, I attempted to redefine the string method on the IPAddr type by appending bytes to an array of string
type IPAddr [4]byte
func (ip IPAddr) String() string {
var s []string
for _, i := range ip {
s = append(s, i)
}
return fmt.Sprintf(strings.Join(s, "."))
}
cannot use i (type byte) as type string in append
playground
There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.
For text or character data, we use new String(bytes, StandardCharsets. UTF_8) to convert the byte[] to a String directly. However, for cases that byte[] is holding the binary data like the image or other non-text data, the best practice is to convert the byte[] into a Base64 encoded string.
copyOf(byte[] original, int newLength) method copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length. For all indices that are valid in both the original array and the copy, the two arrays will contain identical values.
Given a Byte value in Java, the task is to convert this byte value to string type. One method is to create a string variable and then append the byte value to the string variable with the help of + operator. This will directly convert the byte value to a string and add it in the string variable.
Since your type is an array with a small length, so I would recommend just building the string without ranging over the elements:
func (ip IPAddr) String() string {
return fmt.Sprintf("%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3])
}
https://play.golang.org/p/nOSj-EyXuyf
If you want to implement your solution by joining the string slice, you need to convert the bytes to their decimal representation using the strconv
package:
func (ip IPAddr) String() string {
s := make([]string, 0, len(ip))
for _, i := range ip {
s = append(s, strconv.Itoa(int(i)))
}
return strings.Join(s, ".")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With