来自hex String的NSData?

Tra*_*ggs 1 string hex nsdata swift swift2

我知道这个问题已经被要求了ObjectiveC,但我Swift还没有足够强大的音译char *bytes.

所以给定

let string = "600DBEEF"
Run Code Online (Sandbox Code Playgroud)

如何创建NSData代表这4个字节的数字:60 0D BE EF

Tra*_*ggs 7

随着Swift3和新的Foundation Data类型的到来,我终于回过头来:

extension UnicodeScalar {
    var hexNibble:UInt8 {
        let value = self.value
        if 48 <= value && value <= 57 {
            return UInt8(value - 48)
        }
        else if 65 <= value && value <= 70 {
            return UInt8(value - 55)
        }
        else if 97 <= value && value <= 102 {
            return UInt8(value - 87)
        }
        fatalError("\(self) not a legal hex nibble")
    }
}

extension Data {
    init(hex:String) {
        let scalars = hex.unicodeScalars
        var bytes = Array<UInt8>(repeating: 0, count: (scalars.count + 1) >> 1)
        for (index, scalar) in scalars.enumerated() {
            var nibble = scalar.hexNibble
            if index & 1 == 0 {
                nibble <<= 4
            }
            bytes[index >> 1] |= nibble
        }
        self = Data(bytes: bytes)
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,我可以以类似于其打印形式的方式构造Data对象:

Data(hex: "600dBeef")
Run Code Online (Sandbox Code Playgroud)