douxie2007 2012-06-09 14:08
浏览 42
已采纳

在Go中解析字符串中的多个整数?

sorry for the title , i don't know how to say that

i have a questions about this code

func ip2long(ip string) (ret int64) {
  p:= strings.Split(ip, ".")
  n, _:= strconv.Atoi(p[0])
  ret += int64(n)*16777216 
  n, _= strconv.Atoi(p[1])
  ret += int64(n)*65536 
  n, _= strconv.Atoi(p[2])
  ret += int64(n)*256
  n, _= strconv.Atoi(p[3])
  ret += int64(n)

  return 
}

I want to convert an ip address to integer number

you see I have wrote such ugly code

first retrive number from strconv.Atoi then convert it to int64

How to simplify this ?

  • 写回答

3条回答 默认 最新

  • doudou890510 2012-06-09 18:02
    关注

    If you want to parse multiple integers from a string, try the Sscanf function, like this:

    func main() {
        var ip [4] uint32
        addr := "192.168.0.1"
        _, err := fmt.Sscanf(addr, "%d.%d.%d.%d", &ip[0], &ip[1], &ip[2], &ip[3])
        if err != nil {
            fmt.Println(err)
            return
        }
        fmt.Println(ip)
        fmt.Println(ip[0]<<24 + ip[1]<<16 + ip[2]<<8 + ip[3])
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料