Last active
September 12, 2015 03:17
-
-
Save dolphinsue319/e759e85a63ecc4608dc5 to your computer and use it in GitHub Desktop.
解密Siri 講的那串1、0
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 | |
// siri 說出來的2進位字串 | |
let whatSirirSays = ["11100110", "10101001", "10011111", "11100101", "10101111", "10000110"] | |
extension Int8 { | |
init(string str: String){ | |
var rtn: Int8 = 0 | |
var i: Int = 0 | |
for anUnicodeScalar in str.unicodeScalars{ | |
//將字串型態的單一 bit 轉成 00000000, 或 00000001 | |
var bitValue: Int8 = anUnicodeScalar == "1" ? 1:0 | |
/* | |
將它的位元向左移動至原本該 bit 所在的位置 | |
例如:原本是 1000000 在上一步驟是 00000001 現在向左移7個位置成 1000000 的8位元變數 | |
*/ | |
bitValue = bitValue << (7 - i) | |
/* | |
將這個 bit 跟上一個 bit 用 OR 組合起來, 以下解釋它的運算結果 | |
https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Art/bitwiseOR_2x.png | |
*/ | |
rtn = bitValue | rtn | |
i++ | |
} | |
self = rtn | |
} | |
} | |
var data: NSMutableData = NSMutableData() | |
for aWord in whatSirirSays { | |
//將單一字串轉成8位元長度的變數 | |
var aChar = Int8(string: aWord) | |
//將這個 8位元的變數跟上一個變數組合起來 | |
data.appendBytes(&aChar, length: 1) | |
} | |
// 將 data 轉成 String | |
let decodedWord = NSString(data: data, encoding: NSUTF8StringEncoding) | |
println(decodedWord) | |
/* | |
原來 Swift 可以使用 C 的 API!所以其實可以直接用 strtoul 將字串轉成一個8位元的變數 | |
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/InteractingWithCAPIs.html#//apple_ref/doc/uid/TP40014216-CH8-XID_11 | |
*/ | |
// 用 map 產生一個8位元長度變數組成 的 Array | |
var bytes: [UInt8] = whatSirirSays.map{ | |
//用 C 的 strtoul 直接將字串轉成8位元長度的變數 | |
let value = strtoul($0, nil, 2) | |
return UInt8(value) | |
} | |
let decodedString = NSString(bytes: &bytes, length: bytes.count, encoding: NSUTF8StringEncoding) | |
println(decodedString) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment