Good choice for a lightweight checksum algorithm?

后端 未结 9 1701
礼貌的吻别
礼貌的吻别 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:12

    Here's a relatively simple one I've 'invented' - there's no mathematical research behind it but it's extremely fast and works in practice. I've also included the Java equivalent that tests the algorithm and shows that there's less than 1 in 10,000,000 chance of failure (it takes a minute or two to run).

    JavaScript

    function getCrc(s) {
        var result = 0;
        for(var i = 0; i < s.length; i++) {
            var c = s.charCodeAt(i);
            result = (result << 1) ^ c;
        }
        return result;
    }
    

    Java

    package test;
    
    import java.util.*;
    
    public class SimpleCrc {
    
        public static void main(String[] args) {
            final Random randomGenerator = new Random();
            int lastCrc = -1;
            int dupes = 0;
            for(int i = 0; i < 10000000; i++) {
                final StringBuilder sb = new StringBuilder();
                for(int j = 0; j < 1000; j++) {
                    final char c = (char)(randomGenerator.nextInt(128 - 32) + 32);
                    sb.append(c);
                }
                final int crc = crc(sb.toString());
                if(lastCrc == crc) {
                    dupes++;
                }
                lastCrc = crc;
            }
            System.out.println("Dupes: " + dupes);
        }
    
        public static int crc(String string) {
            int result = 0;
            for(final char c : string.toCharArray()) {
                result = (result << 1) ^ c;
            }
            return result;
        }
    }
    

提交回复
热议问题