Last active
September 8, 2017 08:28
-
-
Save lifecube/9decfabdd208822a599fd5dbefa47012 to your computer and use it in GitHub Desktop.
Swift Data extension to support converting data to hexadecimal presented string and construct data by hexadecimal string
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
| import Foundation | |
| extension Data { | |
| func hexDescription() -> String { | |
| return map { String(format: "%02X", $0) } | |
| .joined(separator: "") | |
| } | |
| init?(hexString:String) { | |
| // Convert 0 ... 9, a ... f, A ...F to their decimal value, | |
| // return nil for all other input characters | |
| func decodeNibble(_ u: UInt16) -> UInt8? { | |
| switch(u) { | |
| case 0x30 ... 0x39: | |
| return UInt8(u - 0x30) | |
| case 0x41 ... 0x46: | |
| return UInt8(u - 0x41 + 10) | |
| case 0x61 ... 0x66: | |
| return UInt8(u - 0x61 + 10) | |
| default: | |
| return nil | |
| } | |
| } | |
| let utf16 = hexString.utf16 | |
| var bytes:[UInt8] = [] | |
| var i = utf16.startIndex | |
| while i != utf16.endIndex { | |
| guard let hi = decodeNibble(utf16[i]), | |
| let loIndex = utf16.index(i, offsetBy: 1, limitedBy: utf16.endIndex), | |
| let lo = decodeNibble(utf16[loIndex]) | |
| else { | |
| return nil | |
| } | |
| let value = hi << 4 + lo | |
| bytes.append(value) | |
| i = utf16.index(i, offsetBy: 2, limitedBy: utf16.endIndex) ?? utf16.endIndex | |
| } | |
| self.init(bytes: bytes) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment