Created
June 19, 2018 18:31
-
-
Save kirilltitov/ef8f8b79e9e71caf5a9d1dbcb6c793ef to your computer and use it in GitHub Desktop.
Swift IP string to UInt32 and backward
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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