简体   繁体   English

如何在 Go[lang] 中将字节转换为字符串

[英]How To Convert Bytes Into Strings In Go[lang]

I am new in Go and trying to do Stringers exercise but I am unable to convert bytes to string in Go.我是 Go 的新手并尝试进行纵梁练习,但我无法在 Go 中将bytes转换为string I looked and found a solution string(i[:]) but that is not working.我查看并找到了一个解决方案string(i[:])但这不起作用。 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.干杯,DD。

The "right" way to convert a 4-byte array to a 'dotted quad would be to use the in-built net` package:将 4 字节数组转换为“点四边形”的“正确”方法would be to use the in-built网络 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)

}

change String() to thisString()更改为此

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

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. 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)而在 Golang integer 类型不能直接转换为字符串没有 function 像strconv.Itoa()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])
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM