Re: how to allow integer overflow for calculating hash code of a string?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 





On Thu, Sep 20, 2012 at 1:55 AM, Haifeng Liu <liuhaifeng@xxxxxxxx> wrote:
I want to write a hash function which acts as String.hashCode() in java: hash = hash * 31 + s.charAt(i)... but I got integer out of range error. How can I avoid this? I saw java do not care overflow of int, it just make the result negative.


Use the bitwise AND operator to mask the hash value with 0x3FFFFFF before each iteration:

  hash = (hash & 67108863) * 31 + s.charAt(i);

Craig

[Index of Archives]     [KVM ARM]     [KVM ia64]     [KVM ppc]     [Virtualization Tools]     [Spice Development]     [Libvirt]     [Libvirt Users]     [Linux USB Devel]     [Linux Audio Users]     [Yosemite Questions]     [Linux Kernel]     [Linux SCSI]     [XFree86]

  Powered by Linux