Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a byte array to a string array [duplicate]

Tags:

go

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

like image 909
edkeveked Avatar asked May 28 '18 14:05

edkeveked


People also ask

How do you convert a byte array into a string?

There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.

Can you store a byte array as a string?

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.

How do you copy byte array?

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.

Can we convert byte to string in java?

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.


1 Answers

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, ".")
}
like image 183
Tim Cooper Avatar answered Oct 13 '22 09:10

Tim Cooper