Last active
May 5, 2016 12:14
-
-
Save sketchytech/bb7725323b4a121fbdef6596af0187bd to your computer and use it in GitHub Desktop.
Swift: DIY Base64 conversion (translated from Java on Wikipedia) - result compared to built-in Base64 encoding
This file contains hidden or 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
// a translation of the Java implementation provided here: https://en.wikipedia.org/wiki/Base64 | |
let CODES = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=" | |
func base64Encode(u:[Int]) -> String { | |
var out = "" | |
var b = 0 | |
var i = 0 | |
while i < u.count { | |
b = (u[i] & 0xFC) >> 2 | |
out.append(CODES[CODES.startIndex.advancedBy(b)]) | |
b = (u[i] & 0x03) << 4 | |
if (i + 1 < u.count) { | |
b |= (u[i + 1] & 0xF0) >> 4 | |
out.append(CODES[CODES.startIndex.advancedBy(b)]) | |
b = (u[i + 1] & 0x0F) << 2 | |
if (i + 2 < u.count) { | |
b |= (u[i + 2] & 0xC0) >> 6 | |
out.append(CODES[CODES.startIndex.advancedBy(b)]) | |
b = u[i + 2] & 0x3F | |
out.append(CODES[CODES.startIndex.advancedBy(b)]) | |
} else { | |
out.append(CODES[CODES.startIndex.advancedBy(b)]) | |
out.appendContentsOf("=") | |
} | |
} else { | |
out.append(CODES[CODES.startIndex.advancedBy(b)]) | |
out.appendContentsOf("==") | |
} | |
i += 3 | |
} | |
return out | |
} | |
extension String { | |
func base64EncodedUTF8() -> String { | |
let bytes = [UInt8](self.utf8).map{Int($0)} | |
return base64Encode(bytes) | |
} | |
} | |
let b64Str = "Help me encode using Base64!" | |
b64Str.base64EncodedUTF8() // SGVscCBtZSBlbmNvZGUgdXNpbmcgQmFzZTY0IQ== | |
// confirm that system encoding is the same as the homemade version | |
b64Str.dataUsingEncoding(NSUTF8StringEncoding)?.base64EncodedStringWithOptions([]) == b64Str.base64EncodedUTF8() // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In the real world we'd probably simply write this extension:
and to decode, this: