How to calculate checksum in swift?

Viewed 8425

I want to calculate checksum. My expected answer of crc is 0xE1 But when I run this code it returns 0. I am not getting any solution to do this. Please help me to solve this. Below is my tried code.

My viewController:

    class ViewController: UIViewController {
    var checkSum:UInt8 = 0
    override func viewDidLoad() {
            super.viewDidLoad()
    let bytes = [0x01,0x0B,0x00,0x0B,0x03,0x07,0x12,0x0E,0x0C,0x10,0x09,0x12,0x0C,0x19,0x09,0xFF,0x14]
        for item in bytes {
            print(calculateCheckSum(crc: checkSum, byteValue: UInt8(item)))
        }
    }

func calculateCheckSum(crc:UInt8, byteValue: UInt8) -> UInt8 {

        let generator = 0x1D

        checkSum = crc ^ byteValue

        for _ in 1...8 {
            if (crc & 0x80 != 0) {
                checkSum = (crc << 1) ^ UInt8(Int8(generator))
            }
            else {
                checkSum <<= UInt8(1)
            }
        }
        return crc
    }
}
2 Answers

Rewritten to avoid incorrectly using the global checkSum variable.

func calculateCheckSum(crc:UInt8, byteValue: UInt8) -> UInt8 {
    let generator: UInt8 = 0x1D

    // a new variable has to be declared inside this function
    var newCrc = crc ^ byteValue

    for _ in 1...8 {
        if newCrc & 0x80 != 0 {
            newCrc = (newCrc << 1) ^ generator
        }
        else {
            newCrc <<= 1
        }
    }
    return newCrc
}

Also, it seems you are not using the result of the method correctly:

var checkSum: UInt8 = 0
let bytes = [...]
for item in bytes {
   checkSum = calculateCheckSum(crc: checkSum, byteValue: UInt8(item))
}

print(checkSum)

I just made an extension from this github link and it works to get CRC32 checksum in case anyone needs it.

extension Data {
public func checksum() -> UInt32 {
    let table: [UInt32] = {
        (0...255).map { i -> UInt32 in
            (0..<8).reduce(UInt32(i), { c, _ in
                (c % 2 == 0) ? (c >> 1) : (0xEDB88320 ^ (c >> 1))
            })
        }
    }()
    return ~(self.bytes.reduce(~UInt32(0), { crc, byte in
        (crc >> 8) ^ table[(Int(crc) ^ Int(byte)) & 0xFF]
    }))
} }
Related