Good choice for a lightweight checksum algorithm?

后端 未结 9 1702
礼貌的吻别
礼貌的吻别 2020-12-30 06:04

I find myself needing to generate a checksum for a string of data, for consistency purposes. The broad idea is that the client can regenerate the checksum based on the payl

9条回答
  •  不知归路
    2020-12-30 06:21

    This is a rather old thread but I suspect it is still viewed quite often so - if all you need is a short but reliable piece of code to generate a checksum the Adler32 bit algorithm has to be your choice. Here is the JavaScript code

    function adler32(data)
    {
     var MOD_ADLER = 65521;
     var a = 1, b = 0;
    
     for (var i = 0;i < data.length;i++) 
     {
      a = (a + data.charCodeAt(i)) % MOD_ADLER;
      b = (b + a) % MOD_ADLER;
     }
    
     var adler = a | (b << 16);
     return adler;
    }
    

    The corresponding fiddle demonsrating the algorithm in action is here.

提交回复
热议问题