ios - Checksum and XOR in Swift -
i worte these methods in objective-c. they're checksum , xor nsdata
- (void)xor:(nsmutabledata *)inputdata withkey:(nsdata *)key { unsigned char* inputbytedata = (unsigned char*)[inputdata mutablebytes]; unsigned char* keybytedata = (unsigned char*)[key bytes]; (int = 0; < [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; }
however, i'm not familiar bitwise operators, in swift, these unsafemutablepointer<void>
... things.
can me converting ? (basically, need checksum , xor functions)
1 more things, should put in nsdata/nsmutabledata
extension ?
thank you.
unsafebufferpointer
/unsafemutablebufferpointer
might need now. i've tried translating code swift below. (but code 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) 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 in 0..<data.length { sum += int(b[i]) } return sum & 0xff }
Comments
Post a Comment