7

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?

Violet Giraffe
  • 32,368
  • 48
  • 194
  • 335
  • Why do you want a 64 bit hash? For better avoiding collisions, or just to fill out 64 bits reserved for hash somewhere? If you want to avoid any realistic chance of collision, I'd say you want more bits than just 64: MD5 in the minimum (if you don't care about security aspect, SHA256 or something if you do). Otherwise, just add padding bits to the 32 bit `qHash`. – hyde Feb 25 '14 at 00:11

2 Answers2

9

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;
}
Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313
2

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.

Community
  • 1
  • 1
yshurik
  • 772
  • 5
  • 12
  • Please prefer inline content over link-only answers, even if it is an SE site. – László Papp Feb 24 '14 at 22:17
  • @LaszloPapp: what you mean by inlining content? Is it some special feature? – yshurik Feb 24 '14 at 22:21
  • 1
    @yshurik He meant summarizing the contents of the link here on this page, which saves people a click and ensures the answer doesn't get invalidated if the link breaks. – 3ventic Feb 24 '14 at 22:23