项目中用到了分片上传文件,在校验文件的时候用到了Adler32算法,由于后端是java,调用端是c#,java是直接有这样的算法库,而c#这边好像没有找到现成的算法,所以在网上找到了一个算法。
但是项目中,上片文章中的算法是一次传入文件数据计算出值,但在我的项目中却需要分多次计算。所以对此算法进行部分修改。
public class Adler32
{
public static uint checksum = 1;
private static uint s1 = 1;
private static uint s2 = 0;
/// <summary>Performs the hash algorithm on given data array.</summary>
/// <param name="bytesArray">Input data.</param>
/// <param name="byteStart">The position to begin reading from.</param>
/// <param name="bytesToRead">How many bytes in the bytesArray to read.</param>
public static void ComputeHash(byte[] bytesArray, int byteStart, int bytesToRead)
{
int n;
while (bytesToRead > 0)
{
n = (3800 > bytesToRead) ? bytesToRead : 3800;
bytesToRead -= n;
while (--n >= 0)
{
s1 = s1 + (uint)(bytesArray[byteStart++] & 0xFF);
s2 = s2 + s1;
}
s1 %= 65521;
s2 %= 65521;
}
checksum = ((s2 << 16) | s1);
}
}