Sometimes we need to convert IPv4/IPv6 to integer/decimal for storing purposes. It allows the creation of more efficient database indexes and filter values faster.

Here is how we could do it in a few lines of code in golang:

package main

import (
"fmt"
"math/big"
"net"
)

func Ip2Int(ip net.IP) *big.Int {
i := big.NewInt(0)
i.SetBytes(ip)
return i
}

func main() {
fmt.Println(Ip2Int(net.ParseIP("20.36.77.12")).String())
fmt.Println(Ip2Int(net.ParseIP("2001:0db8:85a3:0000:0000:8a2e:0370:7334")).String())
}

Play with code

Share your thoughts ;)

Happy coding! :rocket:

--

--

Alt

I was looking for a while for different ways of cleaning a string in Golang from listed symbols and did find anything fast. Therefore as a regular developer, I’m just reinventing a wheel.

And here is the solution:

func ClearString(str string, symbols []string) string {
scanner := bufio.NewScanner(strings.NewReader(str))
scanner.Split(bufio.ScanRunes)
out:
var buf bytes.Buffer
for scanner.Scan() {
t := scanner.Text()
for _, s := range symbols {
if s == t {
continue out
}
}
buf.WriteString(scanner.Text())
}
return buf.String()
}

Benchmarking

BenchmarkClearString
BenchmarkClearString-16 200814 5116 ns/op 4416 B/op 5 allocs/op
PASS

Share your thoughts 😜

Happy coding! 🚀

--

--

Andrew Reddikh

Andrew Reddikh

I’m an Entrepreneur, Software Engineer, and Startup soul. Find out more at www.andrew.red