1
0

String+BASE64.swift 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. //
  2. // String+BASE64.swift
  3. // Swifter
  4. //
  5. // Copyright © 2016 Damian Kołakowski. All rights reserved.
  6. //
  7. #if os(Linux)
  8. import Glibc
  9. #else
  10. import Foundation
  11. #endif
  12. extension String {
  13. private static let CODES = [UInt8]("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".utf8)
  14. public static func toBase64(_ data: [UInt8]) -> String {
  15. // Based on: https://en.wikipedia.org/wiki/Base64#Sample_Implementation_in_Java
  16. var result = [UInt8]()
  17. var tmp: UInt8
  18. for index in stride(from: 0, to: data.count, by: 3) {
  19. let byte = data[index]
  20. tmp = (byte & 0xFC) >> 2;
  21. result.append(CODES[Int(tmp)])
  22. tmp = (byte & 0x03) << 4;
  23. if index + 1 < data.count {
  24. tmp |= (data[index + 1] & 0xF0) >> 4;
  25. result.append(CODES[Int(tmp)]);
  26. tmp = (data[index + 1] & 0x0F) << 2;
  27. if (index + 2 < data.count) {
  28. tmp |= (data[index + 2] & 0xC0) >> 6;
  29. result.append(CODES[Int(tmp)]);
  30. tmp = data[index + 2] & 0x3F;
  31. result.append(CODES[Int(tmp)]);
  32. } else {
  33. result.append(CODES[Int(tmp)]);
  34. result.append(contentsOf: [UInt8]("=".utf8));
  35. }
  36. } else {
  37. result.append(CODES[Int(tmp)]);
  38. result.append(contentsOf: [UInt8]("==".utf8));
  39. }
  40. }
  41. return String.fromUInt8(result)
  42. }
  43. }