Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hashing a string to an integer in c++

I am trying to figure out the conversion process for strings to ints. We are doing a program with hashing, in which the key value to be hashed is the name of a state. From my research, it seems like atoi() will not work.

Do I need to break each letter of the word down and individually convert? Do I use ASCII? Am I completely going in the wrong direction?

I am very lost, so ANY information would be fantastic. Thanks!

like image 367
user2109706 Avatar asked Apr 18 '13 05:04

user2109706


People also ask

Can I hash a string?

Hashing is the process of transforming any given key or a string of characters into another value. This is usually represented by a shorter, fixed-length value or key that represents and makes it easier to find or employ the original string.

Can you hash an integer?

The most commonly used method for hashing integers is called modular hashing: we choose the array size M to be prime, and, for any positive integer key k, compute the remainder when dividing k by M. This function is very easy to compute (k % M, in Java), and is effective in dispersing the keys evenly between 0 and M-1.

How do I make a hash for a string?

In order to create a unique hash from a specific string, it can be implemented using their own string to hash converting function. It will return the hash equivalent of a string. Also, a library named Crypto can be used to generate various types of hashes like SHA1, MD5, SHA256 and many more.

Can we use stoi in C?

What Is stoi() in C++? In C++, the stoi() function converts a string to an integer value. The function is shorthand for “string to integer,” and C++ programmers use it to parse integers out of strings. The stoi() function is relatively new, as it was only added to the language as of its latest revision (C++11) in 2011.


1 Answers

From here, there are two function to convert string to uint32_t or uint64_t, convert to uint32_t:

inline uint32_t hash_str_uint32(const std::string& str) {

    uint32_t hash = 0x811c9dc5;
    uint32_t prime = 0x1000193;

    for(int i = 0; i < str.size(); ++i) {
        uint8_t value = str[i];
        hash = hash ^ value;
        hash *= prime;
    }

    return hash;

}

Test:

enter image description here

like image 56
Jayhello Avatar answered Nov 15 '22 16:11

Jayhello