2015-04-01 56 views
5

我在Objective-C中運用了這些方法。他們只是校驗和XOR一些NSDataSwift中的Checksum和XOR

- (void)XOR:(NSMutableData *)inputData withKey:(NSData *)key 
{ 
    unsigned char* inputByteData = (unsigned char*)[inputData mutableBytes]; 
    unsigned char* keyByteData = (unsigned char*)[key bytes]; 
    for (int i = 0; i < [inputData length]; i++) 
    { 
     inputByteData[i] = inputByteData[i]^keyByteData[i % [key length]]; 
    } 
} 

- (Byte)checkSum:(NSMutableData *)data withLength:(Byte)dataLength 
{ 
    Byte * dataByte = (Byte *)malloc(dataLength); 
    memcpy(dataByte, [data bytes], dataLength); 

    Byte result = 0; 
    int count = 0; 
    while (dataLength>0) { 
     result += dataByte[count]; 
     dataLength--; 
     count++; 
    }; 
    result = result&0xff; 
    return result&0xff; 
} 

不過,我不熟悉位運算符,尤其是斯威夫特,這些UnsafeMutablePointer<Void> ......東西。

任何人都可以幫我轉換嗎? (基本上,我需要校驗和和異或函數)
還有一件事情,他們應該在NSData/NSMutableData擴展?

謝謝。

回答

0

斯威夫特3更新:

public extension Data { 

    public mutating func xor(key: Data) { 
     for i in 0..<self.count { 
      self[i] ^= key[i % key.count] 
     } 
    } 


    public func checkSum() -> Int { 
     return self.map { Int($0) }.reduce(0, +) & 0xff 
    } 
} 

你也可以創建另一個功能:xored(key: Data) -> Data
然後你可以連鎖這些運營商:xored(key).checksum()

8

UnsafeBufferPointer/UnsafeMutableBufferPointer可能是你現在需要的。我試過把你的代碼翻譯成下面的Swift。 (但代碼沒有測試好。)

func XOR(inputData: NSMutableData, withKey key: NSData) { 
    let b = UnsafeMutableBufferPointer<UInt8>(start: 
     UnsafeMutablePointer(inputData.mutableBytes), count: inputData.length) 

    let k = UnsafeBufferPointer<UInt8>(start: 
     UnsafePointer(key.bytes), count: key.length) 

    for i in 0..<inputData.length { 
     b[i] ^= k[i % key.length] 
    } 
} 

func checkSum(data: NSData) -> Int { 
    let b = UnsafeBufferPointer<UInt8>(start: 
     UnsafePointer(data.bytes), count: data.length) 

    var sum = 0 
    for i in 0..<data.length { 
     sum += Int(b[i]) 
    } 
    return sum & 0xff 
} 
+1

沒有必要使用'unsafeBitCast'。例如:'let k = UnsafeBufferPointer(start:UnsafePointer (key.bytes),count:key.length)'。 –

+0

@MartinR感謝您的好消息。我的代碼變得更好了。 – findall

+1

謝謝。我會測試它,並標記你的答案爲稍後接受;) –

0

更新了斯威夫特3:

func xor(data: Data, with key: Data) -> Data { 
    var xorData = data 

    xorData.withUnsafeMutableBytes { (start: UnsafeMutablePointer<UInt8>) -> Void in 
     key.withUnsafeBytes { (keyStart: UnsafePointer<UInt8>) -> Void in 
      let b = UnsafeMutableBufferPointer<UInt8>(start: start, count: xorData.count) 

      let k = UnsafeBufferPointer<UInt8>(start: keyStart, count: data.count) 
      let length = data.count 

      for i in 0..<xorData.count { 
       b[i] ^= k[i % length] 
      } 
     } 
    } 

    return xorData 
} 
+0

檢查我的答案:D –