java - Any fast and simple way to hash small byte arrays so that most significant bits are most variable? -


the commonly used methods aggregate hash codes ones suggested generating hash codes byte arrays. typical examples (using aggregate here compact code stackoverflow):

byte[] bytes; var hasha = bytes.aggregate(31, (i, b) => * 31 + b); var hashb = bytes.aggregate(397, (i, b) => (i * 397) ^ b); 

it seems multiplications relatively small, positive numbers affect least significant bits byte arrays handful of elements. same true addition , xor.

this perfect when want load balancing etc. via hash mod algorithm. have algorithm sensitive @ significant side of things. so there simple , fast ways hash, significant bits more "variable" small byte arrays?

first off, checking couple of real test cases, not bad seemed, , second, easy enhance changing seed value (see hashc , hashd):

byte[] bytes = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; (int count = 1; count <= bytes.length; count++) {     var hasha = bytes.take(count).aggregate(31, (i, b) => i*31 + b);     var hashb = bytes.take(count).aggregate(397, (i, b) => (i*397) ^ b);     var hashc = bytes.take(count).aggregate(0xfedcbabc, (i, b) => (i*397) ^ b);     var hashd = bytes.take(count).aggregate(0xfedcbabc, (i, b) => (i*31) + b);     console.writeline(hasha.tostring("x8") + " / " + hashb.tostring("x8") + " / " + hashc.tostring("x8") + " / " + hashd.tostring("x8")); } 

gives following results:

000003c1 / 000267a9 / 3c4d958c / dcba9cc4 00007460 / 03bac114 / 8450ea1d / ba98fbbd 000e17a2 / c89d6c06 / 317b0efb / 98867be5 01b4dca1 / 1c20854d / bbd63b3c / 784900be 34e6b783 / 9e6eb86d / 4b39dc08 / 90d71706 67f038e2 / b1b4010c / a8ba386d / 8a0bc9bf 9616e364 / 94259f9a / a8c9810f / b76d6e27 2cc58923 / be5881d5 / c07d2444 / 364056c0 6beb9b45 / 2f415759 / 82113d7c / 91ca8148 1187cd64 / 4854750c / b4bc5945 / a785a7c1 1f71df26 / 2af98396 / 4816700b / 492f5069 

Comments