Skip to content

Instantly share code, notes, and snippets.

@kirilltitov
Created June 19, 2018 18:31
Show Gist options
  • Save kirilltitov/ef8f8b79e9e71caf5a9d1dbcb6c793ef to your computer and use it in GitHub Desktop.
Save kirilltitov/ef8f8b79e9e71caf5a9d1dbcb6c793ef to your computer and use it in GitHub Desktop.
Swift IP string to UInt32 and backward
func stringIpToInt(_ input: String) -> UInt32 {
var result: UInt32 = 0
var i = 0
for part in input.split(separator: ".") {
result |= UInt32(part)! << ((3 - i) * 8)
i += 1
}
return result
}
func intToIpString(_ input: UInt32) -> String {
let byte1 = UInt8(input & 0xff)
let byte2 = UInt8((input >> 8) & 0xff)
let byte3 = UInt8((input >> 16) & 0xff)
let byte4 = UInt8((input >> 24) & 0xff)
return "\(byte4).\(byte3).\(byte2).\(byte1)"
}
dump(stringIpToInt("127.0.0.1"))
dump(intToIpString(2130706433))
// - 2130706433
// - "127.0.0.1"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment