如何在数组<UInt8>上执行XOR操作?

我正在尝试对数组执行XOR操作。

第一阵列

var first: Array<UInt8> = Array<UInt8>.init(hex: "4C50CF1C2E08")
//equals [76, 80, 207, 28, 46, 8]

第二阵列

var second: Array<UInt8> = Array<UInt8>.init(hex: "91517975190D")
//equals [145, 81, 121, 117, 25, 13, 206]

十六进制输出除外。对于上面的示例,它将是:

DD01B6693705

I am using the CryptoSwift Framework

Found the Doc for XOR.

But I am struggling even to convert by UInt8 Array to one variable which holds a UInt8 to perform the ^. I am grateful for any ideas and hints.

评论
hea
hea

Got it. Thanks to https://stackoverflow.com/a/53296718/558801

extension Data {
    static func ^ (left: Data, right: Data) -> Data {
        if left.count != right.count {
            NSLog("Warning! XOR operands are not equal. left = \(left), right = \(right)")
        }

        var result: Data = Data()
        var smaller: Data, bigger: Data
        if left.count <= right.count {
            smaller = left
            bigger = right
        } else {
            smaller = right
            bigger = left
        }

        let bs:[UInt8] = Array(smaller)
        let bb:[UInt8] = Array (bigger)
        var br = [UInt8] ()
        for i in 0..<bs.count {
            br.append(bs[i] ^ bb[i])
        }
        for j in bs.count..<bb.count {
            br.append(bb[j])
        }
        result = Data(br)
        return result
    }
}
点赞
评论