Generate fixed size hash

1.5k Views Asked by At

I am using the std::hash in cpp utility to generate the hash for the string. My requirement is to generate the fixed size hash of 11 digits. The hash function need not be great to never have collision. The only requirement that I have is to generate the fixed size hash of 11 digits. Any inputs will be great, I can go with some custom hash function also.

#include <iostream>
#include <string>
#include <functional>
#include <iomanip>
#include <unordered_set>
int main()
{
    std::hash<std::string> hash_fn;

    std::string s1 = "Stand back! I've got jimmies!";
    size_t hash1 = hash_fn(s1);
    std::cout << hash1 << '\n'; // OUTPUT: 3544599705012401047

    s1 = "h";
    hash1 = hash_fn(s1);
    std::cout << hash1 << '\n'; // OUTPUT: 11539147918811572172

    return 1;
}
1

There are 1 best solutions below

1
On BEST ANSWER

It's very simple, you can just modulo the result:

size_t fix_11digits(size_t n) { return n % 100000000000LU; }

Usage:

size_t hash1 = fix_11digits(hash_fn(s1));

EDIT:

If you want to get the actual string of the hash, then be aware of the leading zeros:

std::ostringstream ss;
ss << std::setw(11) << std::setfill('0') << hash1;
std::string s{ss.str()};