Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to generate a unique unsigned integer from a string in c++?

I don't need code (you can provide examples in code if you wish) but I would like the theory.

Let's pretend I have the following function:

UINT GenerateID(const char * string);

I would like the function's result to look completely random. I understand that it is impossible to be unique, but that is the best way I could 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 attempting this myself, the results always have roughly the same amount of digits.

like image 621
Larry Avatar asked Apr 15 '13 18:04

Larry


People also ask

How do I convert a string to an int in C++?

One effective way to convert a string object into a numeral int is to use the stoi() function. This method is commonly used for newer versions of C++, with is being introduced with C++11. It takes as input a string value and returns as output the integer version of it.


2 Answers

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

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

like image 69
Kurt Tomlinson Avatar answered Oct 11 '22 12:10

Kurt Tomlinson


Have you looked into std::hash ?

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

like image 25
Nico Avatar answered Oct 11 '22 13:10

Nico