Home > other >  How To Convert Bytes Into Strings In Go[lang]
How To Convert Bytes Into Strings In Go[lang]

Time:08-16

I am new in Go and trying to do Stringers exercise but I am unable to convert bytes to string in Go. I looked and found a solution string(i[:]) but that is not working. Below is my complete code

package main

import (
    "fmt"
)

type IPAddr [4]byte

func (i IPAddr) String() string {
    // not sure how to turn bytes into string ?
   // expected result: from {127, 0, 0, 1} -> 127.0.0.1
    return string(i[:])
}

func main() {
    hosts := map[string]IPAddr{
        "loopback":  {127, 0, 0, 1},
        "googleDNS": {8, 8, 8, 8},
    }
    for name, ip := range hosts {
        fmt.Printf("%v: %v\n", name, ip)
    }
}

expected result is

loopback: 127.0.0.1
googleDNS: 8.8.8.8

any help would be really appreciated.

CHeers, DD.

CodePudding user response:

The "right" way to convert a 4-byte array to a 'dotted quadwould be to use the in-builtnet` package:

package main

import (
  "fmt"
  "net"
)

func main() {
  octets     := []byte{123, 45, 67, 89}
  ip         := net.IP(octets)
  dottedQuad := ip.To4().String()

  fmt.Printf("%v is %s\n", octets, dottedQuad)

}

CodePudding user response:

change String() to this

func (i IPAddr) String() string {
    // return fmt.Sprintf("%d.%d.%d.%d", i[0], i[1], i[2], i[3])
    var res string
    res = strconv.Itoa(int(i[0]))
    for _, v := range i[1:] {
        res  = "."   strconv.Itoa(int(v))
    }
    return res

// or
/*
    var sb strings.Builder

    sb.WriteString(strconv.Itoa(int(i[0])))

    for _, v := range i[1:] {
        sb.WriteString("."   strconv.Itoa(int(v)))
    }
    return sb.String()
*/
}

CodePudding user response:

You can't just output the UTF-8 encoded value as the string the 127 take as the UTF-8 value not the string so you should change the integer to the string first. And in Golang integer type can not directly transform to string without function like strconv.Itoa() or fmt.Sprintf('%d', int)

your code can be like

func (i IPAddr) String() string {
        return return fmt.Sprintf("%v.%v.%v.%v", i[0], i[1], i[2], i[3])
    }
  •  Tags:  
  • go
  • Related