2012-06-09 14:08

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

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

``````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 ?

#### 图片转代码服务由CSDN问答提供 功能建议

``` ``` 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）

返回
}

我想将IP地址转换为整数

您会看到我写了这么难看的代码

首先从strconv.Atoi中检索数字，然后将其转换为int64

如何简化此过程？
``````
` `
``` 写回答 好问题 提建议 关注问题 收藏 分享 邀请回答 ```
``` 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]) } 已采纳该答案 评论 解决 无用 打赏 分享 举报 doushi7761 2012-06-09 14:50 This construct is heavy but appears more natural if you, as you probably should, were catching the parsing errors. This being said, the correct solution to that exact problem is to use the existing net.ParseIP function which builds an IP func ParseIP(s string) IP If you must keep your current function prototype, I suggest this : func ip2long(s string) (ret int64) { bip := ([]byte)(net.ParseIP(s).To4()) return (int64)(bip[0]) * (1 << 24) + (int64)(bip[1]) * (1 << 16) + (int64)(bip[2]) * (1 << 8) + (int64)(bip[3]) } Note that you may add a test on the return of ParseIP (which is nil in case of error) 评论 解决 无用 打赏 分享 举报 douyalin0847 2012-06-09 15:21 I don't recommend it, because you would be ignoring errors, but you can write a function to give you the first value: func first(x int, _ error) int {return x;} Then use first(strconv.Atoi(p[0])) in your code. For the particular code you listed though, I would use the (well tested!) standard library's net.ParseIP() and net.To4() functions: // WARNING untested code!! type InvalidIP string func (InvalidIP ipStr) Error() string { return "Invalid IPv4 address: "+ipStr } func ip2long(ipStr string) (ret int64, err error) { var ip net.IP if ip = net.ParseIP(ipStr); ip == nil { return 0, InvalidIP(ip) } if ip = ip.To4(); ip == nil { return 0, InvalidIP(ip) } for b := range ip { ret <<= 8 ret += b } return ret, nil } Note that the above code adds error checking, and also accepts IPv6 formatted v4 addresses "::FFFF:C0A8:0101". Consider whether you really need an int64 type to represent IP addresses, or whether the standard library's net.IP type is good enough for your purposes. 评论 解决 无用 打赏 分享 举报 报告相同问题？ 提交 关注问题 相关推荐 更多相似问题 在Go中解析字符串中的多个整数？ 2012-06-09 14:08 回答 3 已采纳 If you want to parse multiple integers from a string, try the Sscanf function, like this: func ma 如何在golang中删除字符串中的最后一个字母？ 2019-07-12 09:33 回答 4 已采纳 How to remove the last letter from the string? In Go, character strings are UTF-8 encoded. 如何使用Go将多个字符串解析为模板？ 2017-01-25 15:55 回答 2 已采纳 You may create a new, empty template using template.New() function. Then you may use the Template. Golang：要计算Go中某个字符串中一个或多个子字符串的出现？ 2017-03-10 19:16 回答 2 已采纳 Use a regular expression: https://play.golang.org/p/xMsHIYKtkQ aORb := regexp.MustCompile("A|B") 在golang中替换字符串中的字符 2019-08-01 12:50 回答 2 已采纳 Strings in Go are immutable, you can't change their content. To change the value of a string varia 如何在Go中使用字符串类型获取字符串的十六进制值 2019-04-24 06:14 回答 2 已采纳 You can use strconv.Itoa: byteArray := []byte("Hello, 世界-123..") for _, v := range byteArray { 在Golang中解析Cookie字符串 2015-02-01 11:52 回答 2 已采纳 package main import ( "bufio" "fmt" "net/http" "strings" ) func main() { raw 如何在Golang中的空字符串字段中返回空值？ 2019-03-13 19:43 回答 2 已采纳 Edit: What you want to do is not possible according to the oracle go driver docs: sql.NullStr 为什么PHP中的字符串等于整数0？ php 2018-11-12 07:02 回答 2 已采纳 "a" == 0 evaluates to true. Because any string is converted into an integer when compared with an 一个字符串+一个整数结果是？ c语言 2019-12-03 11:08 回答 3 已采纳 char *q=p+L;表示定义一个指针，指向字符串最后一个元素的地址； 程序功能是判断一个字符串是否是回文数 没有解决我的问题, 去提问```
``` 点击登录 提问题 ◇ 欢迎建议意见◇ 回答问题能得到什么？◇ 如何写出高质量提问和回答？◇ 问答使用帮助文档◇ 问答公告 加急问题 ¥200 win 10安装python库pycld3报错 ¥200 用c语言完成下列课题，所有要求都在长图中，由于课件是英文请自行翻译，悬赏很高望解答 ¥170 急! 面试题请教 - 创建数据库和查询 ¥100 N2N配置supernode，运行一段时间后连接不上了 ¥100 转发视频部分成功部分失败 ¥100 linux开发板使用SQLite出现QSqlDatabase: QSQLITE driver not loaded ¥100 怎么用paddleseg内置的cityscapes相关内容实现城市视频的图像分割 ¥100 电路板上的RTR JTAG ICE接口如何通过仿真器读写，芯片：ksz8995xa\ksz8695x ¥100 渗透文件包 进入软件服务器获取用户权限 是什么原理 ¥100 使用UEditor时，页面显示后端配置项没有正常加载，上传插件不能正常使用！ ```
``` ```
``` window.csdn.sideToolbar = { options: { afterFinished: function () { setTimeout(function () { var helphtml = '<a class="option-box" data-type="help" href="https://ask.csdn.net/questions/7441224" target="_blank">'+'<img src="https://g.csdnimg.cn/side-toolbar/2.5/images/bangzhucopy.png" alt="" srcset="">'+ '<span class="show-txt">帮助</span></a>'; \$('.csdn-side-toolbar > a:last').before(helphtml); }, 300); }, contentEl: document.getElementsByClassName('floor')[0] } } ```