由整形转换成IP字符串如:4284928154 到 255.102.208.154,这个问题效率最高的方法是:
func InetNtoA3(i int64) string {
return net.IP{byte(i >> 24), byte(i >> 16), byte(i >> 8), byte(i)}.String()
}
从net.IP的源代码来看在最后String()之前,前面的过程都是以byte的方式进行的,应该是最优算法了。
作为参照,把网上常见的另外两种转换方式放在一起做对比测试:
long2ip.go
package main
import (
"bytes"
"fmt"
"net"
"strconv"
)
func InetNtoA1(ip int64) string {
return fmt.Sprintf("%d.%d.%d.%d",
byte(ip>>24), byte(ip>>16), byte(ip>>8), byte(ip))
}
func InetNtoA2(ipInt int64) string {
ipSegs := make([]string, 4)
var len int = len(ipSegs)
buffer := bytes.NewBufferString("")
for i := 0; i < len; i++ {
tempInt := ipInt & 0xFF
ipSegs[len-i-1] = strconv.FormatInt(tempInt, 10)
ipInt = ipInt >> 8
}
for i := 0; i < len; i++ {
buffer.WriteString(ipSegs[i])
if i < len-1 {
buffer.WriteString(".")
}
}
return buffer.String()
}
func InetNtoA3(i int64) string {
return net.IP{byte(i >> 24), byte(i >> 16), byte(i >> 8), byte(i)}.String()
}
func main() {
var IP int64 = 4284928154
fmt.Println(InetNtoA1(IP))
fmt.Println(InetNtoA2(IP))
fmt.Println(InetNtoA3(IP))
}
long2ip_test.go
package main
import (
"testing"
)
func BenchmarkInetNtoA1(b *testing.B) {
for i := 0; i < b.N; i++ {
InetNtoA1(4284928154)
}
}
func BenchmarkInetNtoA2(b *testing.B) {
for i := 0; i < b.N; i++ {
InetNtoA2(4284928154)
}
}
func BenchmarkInetNtoA3(b *testing.B) {
for i := 0; i < b.N; i++ {
InetNtoA3(4284928154)
}
}
测试结果:
[root@dev long2ip]# go test --bench .
goos: linux
goarch: amd64
pkg: long2ip
BenchmarkInetNtoA1-4 4373192 266 ns/op
BenchmarkInetNtoA2-4 4549550 267 ns/op
BenchmarkInetNtoA3-4 25693334 51.0 ns/op
PASS
ok long2ip 4.294s