1
Vote

Incorrect bit conversion for checksums

description

Ive noticed when hashing a file with (CRC32, CRC64, FNV, anything that converts a uint or ulong to a byte array), you would get a incorrect value. I narrowed this down to the project file: HashResult.cs

An easy fix for this is replace the following code with my working code:
    public HashResult(uint a_hash)
    {
        m_hash = BitConverter.GetBytes(a_hash);
    }
replace that with this:
    public HashResult(uint a_hash)
    {
        m_hash = new[]
        {
            (byte)((a_hash >> 24) & 0xff),
            (byte)((a_hash >> 16) & 0xff),
            (byte)((a_hash >> 8) & 0xff),
            (byte)(a_hash & 0xff)
        };

       // m_hash = BitConverter.GetBytes(a_hash);
    }
also replace:
    public HashResult(ulong a_hash)
    {
        m_hash = BitConverter.GetBytes(a_hash);
    }
with
    public HashResult(ulong a_hash)
    {
        m_hash = UInt64_To_BE(a_hash);
    }

    private void UInt64_To_BE(ulong n, byte[] bs, int off)
    {
        UInt32_To_BE((uint)(n >> 32), bs, off);
        UInt32_To_BE((uint)(n), bs, off + 4);
    }

    private static void UInt32_To_BE(uint n, byte[] bs, int off)
    {
        bs[off] = (byte)(n >> 24);
        bs[off + 1] = (byte)(n >> 16);
        bs[off + 2] = (byte)(n >> 8);
        bs[off + 3] = (byte)(n);
    }

    private byte[] UInt64_To_BE(ulong n)
    {
        byte[] bs = new byte[8];
        UInt64_To_BE(n, bs, 0);

        return bs;
    }

This helped me fix the problems with the checksums and everything else is still working.

comments