Skip to content

Instantly share code, notes, and snippets.

@kerkerj
Last active June 6, 2018 08:35
Show Gist options
  • Save kerkerj/18199fdea790cd220c6e6a37c138a798 to your computer and use it in GitHub Desktop.
Save kerkerj/18199fdea790cd220c6e6a37c138a798 to your computer and use it in GitHub Desktop.
Compress/Extract IPv4 address in golang
package main
import (
"fmt"
)
func main() {
ip := "192.168.0.1"
encodedIP := Encode(ip)
fmt.Println("Encode: " + ip)
fmt.Println(encodedIP)
fmt.Printf("Decode: %d\n", encodedIP)
fmt.Println(Decode(encodedIP))
}
func Decode(encoded int) string {
a := (encoded >> 24) & 0xFF
b := (encoded >> 16) & 0xFF
c := (encoded >> 8) & 0xFF
d := encoded & 0xFF
return fmt.Sprintf("%d.%d.%d.%d", a, b, c, d)
}
func Encode(ip string) int {
var nums [4]int
_, err := fmt.Sscanf(ip, "%d.%d.%d.%d", &nums[0], &nums[1], &nums[2], &nums[3])
if err != nil {
panic(err)
}
return (nums[0] << 24) | (nums[1] << 16) | (nums[2] << 8) | nums[3]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment