Swift와 하드웨어 연결 캡슐화 방법

4116 단어
Data-to-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 ''), 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 Edition
+ (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
    }

좋은 웹페이지 즐겨찾기