Skip to content

Instantly share code, notes, and snippets.

@42atomys
Created September 17, 2024 13:34
Show Gist options
  • Save 42atomys/53344aefb69f5d173211fdb5b598e8c2 to your computer and use it in GitHub Desktop.
Save 42atomys/53344aefb69f5d173211fdb5b598e8c2 to your computer and use it in GitHub Desktop.
[Go brain breaker for everyone] Do a IP Version validator only in bitwise
package main
// IPVersion return the version of an IP (4 or 6) only by using bitwise with zero allocation.
// This implementation are 17.6% faster than no bitwise implementation but create an unreadable
// code. I challenge myself to create that only for fun. That's fun, and I wanna to store and share
// somewhere so that is it !
func IPVersion(ipStr string) (int, error) {
var flags uint8 = 0
for i := 0; i < len(ipStr); i++ {
c := ipStr[i]
flags |= ((c ^ '.') * 1) | ((c ^ ':') * 2)
}
if flags == 1 || flags == 2 {
return 4 + 2*(int(flags)>>1), nil
}
return 0, errors.New("invalid IP address format")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment