Pham Hoan Pham Hoan - 1 year ago 192
iOS Question

Checksum and XOR in Swift

I worte these methods in Objective-C. They're just checksum and XOR some


- (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];
result = result&0xff;
return result&0xff;

However, I'm not familiar with Bitwise operators, especially in Swift, with these
... things.

Can anybody help me converting this ? (Basically, I need checksum and XOR functions)

One more things, should they be put in
extension ?

Thank you.

Answer Source

UnsafeBufferPointer/UnsafeMutableBufferPointer might be what you need now. I've tried translating your code into Swift below. (But the code is not tested well.)

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download