众所周知,Java没有无符号类型。我需要将一个C#代码片段(使用uint)转换成Java。我的代码如下:
private const int ROLLING_WINDOW = 7;
private const int HASH_PRIME = 0x01000193;
private unit h1, h2, h3, n;
private byte[] window;
//...
private uint roll_hash(byte c)
{
h2 -= h1;
h2 += (uint)ROLLING_WINDOW * c;
h1 += c;
h1 -= window[n % ROLLING_WINDOW];
window[n % ROLLING_WINDOW] = c;
n++;
h3 = (h3 << 5);
h3 ^= c;
return h1 + h2 + h3;
}
private static uint sum_hash(byte c, uint h)
{
h *= HASH_PRIME;
h ^= c;
return h;
}
在Java中,我使用long
代替uint
,但有时结果会给出负值。解决方案是使用无符号运算符。
经过一些搜索,发现可以使用0xFFFFFFFFL,但由于时间紧迫,这有点复杂。希望有人能帮我解决这个问题。
谢谢
n
转换为从 0 到 0xFFFFFFFFL 的无符号值,执行 % 操作,然后再转换回int
。第二种方法只是确保该值始终介于0
和6
之间。 - Peter Lawrey