Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Built-in 64-bit hash function for QString?

Tags:

c++

hash

qt

qhash

qHash(const QString&) returns uint, which is 32-bit. Is there any standard Qt way of getting 64-bit hash for a string on 32-bit system? Or do I have to implement a hash function myself?

like image 690
Violet Giraffe Avatar asked Feb 13 '23 17:02

Violet Giraffe


2 Answers

This is one way of doing it. It's cross-platform, in the sense that given string will yield same hash no matter what the platform is. It could be certainly further optimized by removing the dependence on QDataStream and using the byte-flipping functions as necessary to massage the endianness.

qint64 hash(const QString & str)
{
  QByteArray hash = QCryptographicHash::hash(
    QByteArray::fromRawData((const char*)str.utf16(), str.length()*2),
    QCryptographicHash::Md5
  );
  Q_ASSERT(hash.size() == 16);
  QDataStream stream(&hash);
  qint64 a, b;
  stream >> a >> b;
  return a ^ b;
}
like image 159
Kuba hasn't forgotten Monica Avatar answered Feb 16 '23 05:02

Kuba hasn't forgotten Monica


I am afraid there is no standard way in Qt for 64-bit hashing for QStrings. But if you go ahead with implementing hash by yourself then it makes sense to study this: https://softwareengineering.stackexchange.com/questions/49550/which-hashing-algorithm-is-best-for-uniqueness-and-speed which will give you a lot of info about hashing strings with code examples.

like image 44
yshurik Avatar answered Feb 16 '23 06:02

yshurik