我在Objective-C中对这些方法进行了研究。它们仅仅是校验和,而XOR是NSData
- (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;
}
但是,我不熟悉Bitwise运算符,特别是在Swift中,使用这些UnsafeMutablePointer<Void>
......事物。
有人可以帮我转换吗? (基本上,我需要校验和和XOR功能)
还有一件事,是否应该加入NSData/NSMutableData
扩展名?
谢谢。
答案 0 :(得分:9)
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 :(得分:1)
Swift 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()
答案 2 :(得分:0)
针对Swift 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
}
答案 3 :(得分:0)
快速支持运算符重载,因此您可以轻松进行{{1}}。我为xor编写了非相似大小数据的扩展。
let xorData = data1 ^ data2