What is the best way to create a unique unsigned integer from a string in C ++?

I don't need code (you can provide examples in code if you want), but I would like this theory.

Suppose I have the following function:

UINT GenerateID(const char * string); 

I want the result of the function to look completely random. I understand that it is impossible to be unique, but this is the best way to explain my desire.

 GenerateID("123"); //Could result in 999 GenerateID("123"); //Must also result in 999 GenerateID("124"); //Should result in something completely different 

When trying this, the result itself always has approximately the same number of digits.

+4
source share
3 answers

You are looking for a hash function. The hash function takes an input of arbitrary length and converts it to a unique number (often hexadecimal).

Check out this page for an example of how the SHA-1 hash works: http://hash.online-convert.com/sha1-generator

+5
source

Have you looked at std :: hash?

http://en.cppreference.com/w/cpp/utility/hash

+4
source

It's impossible. Suppose your int argument is 32 bits. The text string will be made of ' ' , a-zA-Z and 0-9 and half a dozen punctuation marks, for a total of about 1 + 2 * 26 + 10 + 6 = 69 characters. For strings of 6 characters, you already have more possible strings than integer values ​​(log (2 ^ 32) / log (69) = 5.23). Use a long long of 64 bits and you are done with 11 characters.

As the other answers say, you can use a hash function (there are a lot of floats around it) that will display strings in integers and (hopefully) distribute them equally across the selected range of integers.

There are methods for constructing perfect hash functions that, for a fixed set of lines, generate a function and a range that is not too large, which does not guarantee collisions (no two lines give a single whole).

If this is used in the program, and the lines can be controlled by an attacker, you are subjected to attacks of algorithmic complexity (an attacker can flood you with lines that collide).

+1
source

All Articles