Search code examples
c++qthashqhash

Built-in 64-bit hash function for QString?


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?


Solution

  • 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;
    }