来自十六进制字符串的 NSData?

NSData from hex String?

我知道 ObjectiveC 已经问过这个问题,但我的 Swift 还不够强大,无法音译 char *bytes 内容。

如此给出

let string = "600DBEEF"

如何创建代表这 4 个字节的 NSData60 0D BE EF

在 swift、XCode beta 6

中回答
    let string = "600DBEEF"

    let length = string.characters.count


    let rawData = UnsafeMutablePointer<CUnsignedChar>.alloc(length/2)
    var rawIndex = 0

    for var index = 0; index < length; index+=2{
      let single = NSMutableString()
      single.appendString(string.substringWithRange(Range(start:string.startIndex.advancedBy(index), end:string.startIndex.advancedBy(index+2))))
      rawData[rawIndex] = UInt8(single as String, radix:16)!
      rawIndex++
    }

    let data:NSData = NSData(bytes: rawData, length: length/2)
    rawData.dealloc(length/2)

随着 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)
    }
}

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

Data(hex: "600dBeef")