Is there a way to convert a hexadecimal string to base64 in Swift? For example, I would like to convert:
BA5E64C0DE
to:
ul5kwN4=
It's possible to convert a normal string to base64 by using:
let hex: String = "BA5E64C0DE"
let utf8str: NSData = hex.dataUsingEncoding(NSUTF8StringEncoding)!
let base64Encoded: NSString = utf8str.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
let base64: String = (base64Encoded as String)
But this would give a result of:
QkE1RTY0QzBERQ==
Because it's just treating the hex as a normal UTF-8 String, and not hexadecimal.
It's possible to convert it to base64 correctly by looping through every six hex characters and converting it to it's four respective base64 characters, but this would be highly inefficient, and is just plain stupid (there would need to be 17,830,160 if statements):
if(hex == "000000"){base64+="AAAA"}
else if(hex == "000001"){base64+="AAAB"}
else if(hex == "000002"){base64+="AAAC"}
else if(hex == "BA5E64"){base64+="ul5k"}
//...
It would be nice if there was something like this:
let hex: String = "BA5E64C0DE"
let data: NSData = hex.dataUsingEncoding(NSHexadecimalEncoding)!
let base64Encoded: NSString = data.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
let base64: String = (base64Encoded as String)
But sadly, there's no NSHexadecimalEncoding
. Is there any efficient way to convert a hexadecimal string to it's base64 representation in Swift?