-1

I want to create a unique id from 3 input numbers. I don't care what the output is, just as long as it is unique. The input numbers are:

NSNumber num
NSUInteger hash
int i

The output should be:

unsigned int id

I don't care about losing precision from any of the input numbers, so I am thinking about calculating the id as:

id = (unsigned int)num + (unsigned int)hash + (unsigned int)i

But there are two problems that I see:

What happens at integer overflow

I'm having problems finding documentation about what happens at integer overflow in Objective-C.

The best source I have found is this article that says that the result is undefined: http://www.sicpers.info/2013/01/what-happens-when-you-add-one-to-an-integer/

That's not good. I wouldn't mind it starting from 0 again, but undefined is not a unique id.

How casting to unsigned int is implemented

I haven't found any information about how casting to unsigned int is implemented. Just interpreting the existing bits as an unsigned int would work fine for me. But casting wouldn't work as intended for me if the result is ever undefined or something like that.

I don't know what the best way forward is.

How should I calculate a unique id that is an unsigned int from various other number types?

user1283776
  • 19,640
  • 49
  • 136
  • 276
  • 1
    What will this unique ID be used for? If it's e.g. a sub-class's hash based on the hash of the base class, you might refer here: http://stackoverflow.com/questions/254281/best-practices-for-overriding-isequal-and-hash. Some of the answers and comments specifically address signed overflow, and why it doesn't matter when calculating a hash value (i.e. just b/c it's __undefined__ doesn't mean it isn't __useful__). Also, your calculation doesn't guarantee uniqueness: for the same value of hash, what if num = 2 and i = 1 in one case, but num = 1 and i = 2 in another? See same ref. – fullofsquirrels Aug 30 '16 at 15:27
  • 1
    What you want is impossible. You could calculate a hash but hash is never unique, by design. If you have 3 numbers and you want an unique identifier, that you need your identifier to contain all 3 numbers, therefore the length of the identifier will be the sum of of the lengths of the individual numbers. `NSNumber` holds a double, therefore 64 bits + at least 32 bits for both integers. You need a type capable of holding 128 bit numbers. – Sulthan Aug 30 '16 at 15:39

1 Answers1

0

Consider hashing a string representation of those values:

NSNumber *num;
NSUInteger hash;
int i;

NSString *string = [NSString stringWithFormat:@"%@%lu%d", num, (unsigned long)hash, i];
NSUInteger myId = [string hash];
danh
  • 62,181
  • 10
  • 95
  • 136
  • Hash won't be a unique identifier. Also, why would you bring strings into the picture? You can calculate a hash directly from numeric values. – Sulthan Aug 30 '16 at 15:41