如何将字符串转换为十六进制数据?

时间:2018-02-10 07:25:31

标签: javascript ionic-framework

我很困惑将字符串转换为十六进制数据。 http://www-01.ibm.com/support/docview.wss?uid=swg21607887 我的语言代码很快。

func stringToBytes(hexstring: String) -> Data? {
    var data = Data(capacity: hexstring.characters.count / 2)

    let regex = try! NSRegularExpression(pattern: "[0-9a-f]{1,2}", options: .caseInsensitive)
    regex.enumerateMatches(in: hexstring, range: NSMakeRange(0, hexstring.utf16.count)) { match, flags, stop in
        let byteString = (hexstring as NSString).substring(with: match!.range)
        var num = UInt8(byteString, radix: 16)!
        data.append(&num, count: 1)
    }

    guard data.count > 0 else { return nil }

    return data
}

0 个答案:

没有答案