Pure Danger Tech


navigation
home

Numeric buggery

18 Jan 2008

Quick, how is this broken: [source:java]

// slot an identifier into a bucket

int getBucketIndex(long id, int buckets) {

return ((int) id) % buckets;

}

[/source]

This kind of code exists to pick a bucket to slot an identifier into. The problem here is the downcast from the long to an int. Downcasting a long with the 31st bit set to an int will return a negative number and modding a negative number will return a negative number, which is never a good index into an array. :)

One solution is to unset the bit: [source:java]

int getBucketIndex(long id, int buckets) {

return (((int) id) & 0x7fffffff) % buckets;

}

[/source]