Skip to content

unit Crc

em.coremark/Crc.em
package em.coremark

import Utils

module Crc

    type sum_t: Utils.sum_t

    function add16(val: int16, crc: sum_t): sum_t
    function addU32(val: uint32, crc: sum_t): sum_t

private:

    function update(data: uint8, crc: sum_t): sum_t

end

def add16(val, crc)
    auto v = <uint16>val
    crc = update(<uint8>v, crc)
    crc = update(<uint8>(v >> 8), crc)
    return crc
end

def addU32(val, crc)
    crc = add16(<int16>val, crc)
    crc = add16(<int16>(val >> 16), crc)
    return crc
end

def update(data, crc)
    auto i = <uint8>0
    auto x16 = <uint8>0
    auto carry = <uint8>0
    for auto i = 0; i < 8; i++
        x16 = <uint8>((data & 1) ^ (<uint8>crc & 1))
        data >>= 1
        if x16 == 1
            crc ^= 0x4002
            carry = 1
        else
            carry = 0
        end
        crc >>= 1
        if carry
            crc |= 0x8000
        else
            crc &= 0x7fff
        end
    end
    return crc
end