String形式的IP地址和Int类型互转函数
![Golang(Go语言)IP地址转换函数](https://imgs.yssmx.com/Uploads/2023/11/745904-1.gif)
![Golang(Go语言)IP地址转换函数](https://imgs.yssmx.com/Uploads/2023/11/745904-2.gif)
1 package main 2 3 import ( 4 "fmt" 5 "strconv" 6 "strings" 7 ) 8 9 func main() { 10 ip1 := `172.16.1.2` 11 ipInt1 := 2886729986 12 fmt.Printf("%s转换为int类型:%d\n", ip1, *ip2int(&ip1)) 13 fmt.Printf("%d转换为string类型:%s\n", ipInt1, *int2ip(&ipInt1)) 14 } 15 16 func ip2int(ip *string) *int { 17 ipSegs := strings.Split(*ip, ".") 18 result := 0 19 for i, v := range ipSegs { 20 seg, _ := strconv.Atoi(v) 21 seg <<= (3 - i) * 8 22 result |= seg 23 } 24 return &result 25 } 26 27 func int2ip(ipInt *int) *string { 28 var ipSegs []string 29 for i := 0; i < 4; i++ { 30 ipSegs = append(ipSegs, strconv.Itoa(*ipInt>>((3-i)*8)&255)) 31 } 32 result := strings.Join(ipSegs, ".") 33 return &result 34 }
输出如下:
文章来源:https://www.toymoban.com/news/detail-745904.html
文章来源地址https://www.toymoban.com/news/detail-745904.html
到了这里,关于Golang(Go语言)IP地址转换函数的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!