Reputation: 1045
I'm not a mathematician so this may be a stupid question...but - is there any way to translate IP addresses into integers between 1 and 3, whereby there will A) be an equal distribution of 1's, 2's and 3's and B) each IP address will always translate to the same integer? (in essence, a hash).
I'm using 3 as an example - ideally I'd like the range limit to be customizable.
$highest_allowed_integer = 3; $integer = get_evenly_distributed_but_always_identical_integer($_SERVER["REMOTE_ADDR"],$highest_allowed_integer);
Thanks!
Upvotes: 1
Views: 308
Reputation: 6303
I don't know the distribution of IP addresses or how important it is that they be uniform, but one thing you could try would be to add up all of the digits in the IP address and then mod that by 3.
Upvotes: 1
Reputation: 72336
Yes (as long as you're not too strict about what "equal distribution" means).
The simple way other people have already suggested involves http://en.wikipedia.org/wiki/Modular_arithmetic where 3 is the "modulus".
Upvotes: 0
Reputation: 210455
Treat the entire IPv4 address as a number in base 256 (that means 4.3.2.1 would translate to (4 << 24) + (3 << 16) + (2 << 8) + 1
), then mod it by 3, and then add 1.
On a little digression, you might want to look into the concept of hashing.
Upvotes: 7