Given a number, how can I create a unique key from that number. This key should never be repeated when given different number. and when the same number is provided it should give back the same key that it generated earlier, i need this in my application. pls can you suggest any algorithm
Edited : sorry guys i changed the Q when you guys were answering the Q i thought the above Q be a better way of asking, my Q is in my B-tree i am storing the ipaddress (src ip and dst ip) of ipv4 i am generating the key for that using the destination ip, for eg: if i have a address 172.28.6.100 i generate a key using the last two bytes as 600 (6*100) now i have to store even the ipv6 address how can i generate a key for that i need to generate a uniqe key for each address.
Your algorithm (from the original question, where you stated you were generating a key
c*dfrom the IP addressa.b.c.d) doesn’t even guarantee uniqueness for your IPv4 addresses.172.28.6.12will have an identical key to172.28.12.6and9.45.3.24and10.1.72.1(among others).That is an inevitable outcome of hashing where you map many items to one key.
My question is: why are you hashing. You can fit an IPv4 address into four bytes and an Ipv6 one into sixteen bytes. They’re not so large that you couldn’t use the entire address as the key, surely?
And, even if they are too large, if your requirement is to be unique across the entire allowable range of IP addresses, you may have to do that anyway. The only way to guarantee uniqueness is to limit the input values somehow.
Since you’ve changed your question to remove the specifics, I’ll add this addendum. The reasoning behind my answer doesn’t change.
If you’re hashing data to generate keys, there are only two ways to guarantee uniqueness of the keys:
The first of those buys you very little. It’s sometimes useful to map sparse data to contiguous indexes for efficient lookups but will not save you any space.
The second is often used where you know the data will be limited such as (1) all your IP addresses start with
10.1or they’re all integers between 1000 and 1099.But, unless you choose one of those limitations, there’s no way to guarantee there won’t be a key collision.