十六进制字符串的NSData? [英] NSData from hex String?

查看:135
本文介绍了十六进制字符串的NSData?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题已被要求为 ObjectiveC ,但我的 Swift 还不够强大 char * bytes 的东西。

I know this question has been asked for ObjectiveC, but my Swift isn't strong enough yet to transliterate the char *bytes stuff.

给出

let string = "600DBEEF"

如何创建一个 NSData 表示这4个字节: 60 0D BE EF

How do I create an NSData which represents those 4 bytes: 60 0D BE EF?

推荐答案

随着Swift3和新的基础数据类型的到来,我终于回到了这里:

With the arrival of Swift3 and the new Foundation Data type, I finally circled back to this:

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对象:

Now I can construct Data objects in a fashion similar to their printed form:

Data(hex: "600dBeef")

这篇关于十六进制字符串的NSData?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆