Swift与硬件打交道封装的方法

Data转HexString

///Data转String
    func hexString(data: Data) -> String {
        return data.withUnsafeBytes({ (bytes: UnsafePointer) -> String in
            let buffer = UnsafeBufferPointer(start: bytes, count: data.count)
            return buffer.map{String(format: "%02hhx", $0)}.reduce("", {$0 + $1})
        })
    }

或者

extension Data{
    
    ///Data转HexString
    func hexString() -> String {
        return self.withUnsafeBytes({ (bytes: UnsafePointer) -> String in
            let buffer = UnsafeBufferPointer(start: bytes, count: self.count)
            return buffer.map{String(format: "%02hhx", $0)}.reduce("", {$0 + $1})
        })
    }
}

HexString转Data

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: characters.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
    }
    
}

hexString与Data互转OC版

+ (NSData *)dataFromHex:(NSString *)hexString {
    
    if (hexString == nil || hexString.length %2 != 0 || hexString.length == 0) return nil;
    NSString *upper = [hexString uppercaseString];
    Byte bytes[hexString.length/2];
    for (int i = 0; i < hexString.length; i=i+2) {
        int high = [self unichar2int:[upper characterAtIndex:i]];
        int low = [self unichar2int:[upper characterAtIndex:i+1]];
        if (high == -1 || low == -1) return nil;
        bytes[i/2] = high * 16 + low;
    }
    return [NSData dataWithBytes:bytes length:hexString.length/2];
}

+ (int)unichar2int:(int)input {
    if (input >= '0' && input <= '9') {
        return input - 48;
    } else if (input >= 'A' && input <= 'F') {
        return input - 55;
    } else {
        return -1;
    }
}

+ (NSString *)hexFromData:(NSData *)data {
    
    if (data == nil) return nil;
    Byte *bytes = (Byte *)data.bytes;
    NSMutableString *str = [NSMutableString string];
    for (int i=0; i

进制转换

extension Int {
    // 10进制转2进制
    var toBinary: String {
        return String(self, radix: 2, uppercase: true)
    }
    // 10进制转16进制
    var toHexa: String {
        return String(self, radix: 16)
    }
}

extension String {
    // 16进制转10进制
    var hexaToDecimal: Int {
        return Int(strtoul(self, nil, 16))
    }
    // 16进制转2进制
    var hexaToBinary: String {
        return hexaToDecimal.toBinary
    }
    // 2进制转10进制
    var binaryToDecimal: Int {
        return Int(strtoul(self, nil, 2))
    }
    // 2进制转16进制
    var binaryToHexa: String {
        return binaryToDecimal.toHexa
    }
}

计算字符串16进制长度

/// 计算字符串16进制长度
    ///
    /// - Parameters:
    ///   - str: 字符串
    ///   - bytes: 计算结果占几个字节
    /// - Returns: 16进制结果
    func calculateStringLenth(str: String, bytes: Int) -> String{
        let length = str.characters.count % 2 == 0 ? str.characters.count / 2 : str.characters.count / 2 + 1
        var hexLength = length.toHexa
        while  hexLength.characters.count / 2 != bytes{
            hexLength = "0" + hexLength
        }
        return hexLength
    }

你可能感兴趣的:(Swift与硬件打交道封装的方法)