(iOS, Swift)十六进制字符串转Data,Data转十六进制String Data,NSData,bytes[UInt8]互转

1.十六进制String(字符串)转Data

1.1 方法一(推荐):

extension String {

    /// Create `Data` from hexadecimal string representation
    ///
    /// This takes a hexadecimal representation and creates a `Data` object. Note, if the string has any spaces or non-hex characters (e.g. starts with '<' and with a '>'), those are ignored and only hex characters are processed.
    ///
    /// - returns: Data represented by this hexadecimal string.

    func hexadecimal() -> Data? {
        var data = Data(capacity: self.count / 2)

        let regex = try! NSRegularExpression(pattern: "[0-9a-f]{1,2}", options: .caseInsensitive)
        regex.enumerateMatches(in: self, range: NSMakeRange(0, utf16.count)) { match, flags, stop in
            let byteString = (self 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
    }

}

1.2 方法二:

 //将十六进制字符串转化为 Data
    func data(from hexStr: String) -> Data {
        var hexStr1 = ""
        if hexStr.count % 2 != 0 {
            hexStr1 = "0" + hexStr
        }else {
            hexStr1 = hexStr
        }
        let bytes = self.bytes(from: hexStr1)
        return Data(bytes: bytes)
    }

    // 将16进制字符串转化为 [UInt8]
    // 使用的时候直接初始化出 Data
    // Data(bytes: Array<UInt8>)
   func bytes(from hexStr: String) -> [UInt8] {
//        print("hexStr:\(hexStr)")
        assert(hexStr.count % 2 == 0, "输入字符串格式不对,8位代表一个字符")
        var bytes = [UInt8]()
        var sum = 0
        // 整形的 utf8 编码范围
        let intRange = 48...57
        // 小写 a~f 的 utf8 的编码范围
        let lowercaseRange = 97...102
        // 大写 A~F 的 utf8 的编码范围
        let uppercasedRange = 65...70
        for (index, c) in hexStr.utf8CString.enumerated() {
            var intC = Int(c.byteSwapped)
            if intC == 0 {
                break
            } else if intRange.contains(intC) {
                intC -= 48
            } else if lowercaseRange.contains(intC) {
                intC -= 87
            } else if uppercasedRange.contains(intC) {
                intC -= 55
            } else {
                assertionFailure("输入字符串格式不对,每个字符都需要在0~9,a~f,A~F内")
            }
            sum = sum * 16 + intC
            // 每两个十六进制字母代表8位,即一个字节
            if index % 2 != 0 {
                bytes.append(UInt8(sum))
                sum = 0
            }
        }
//    print(bytes)
    print(bytes.count)
        return bytes
    }

2.Data转十六进制String

extension Data {

    /// Create hexadecimal string representation of `Data` object.
    ///
    /// - returns: `String` representation of this `Data` object.

    func hexadecimal() -> String {
        return map { String(format: "%02x", $0) }
            .joined(separator: "")
    }
}

3.Data,NSData,bytes[UInt8]互转

playground
在这里插入图片描述

bytes: [UInt8]

let data:Data = Data.init(bytes: bytes);         
let nsdata:NSData = NSData.init(bytes: bytes, length: bytes.count);

data: Data

let bytes: [UInt8] = [UInt8](data)  
let nsdata: NSData = NSData(data: data)

nsdata: NSData

let bytes: [UInt8] = [UInt8](nsdata)
let data: Data = nsdata as Data

参考博客:

(iOS, Swift)十六进制转Data,十六进制转整形,Data转String
swift 16进制String和Data相互转换
Swift中,把NSData转换为Byte数组的三种方法

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页