QT-如何将字符串转成唯一整型ID

要将一个字符串转换为唯一的整型,可以使用哈希函数实现。以下是使用Qt框架的代码示例:

#include 

quint32 stringToUniqueInt(const QString& str)
{
    QByteArray byteArray = QCryptographicHash::hash(str.toUtf8(), QCryptographicHash::Md5);
    quint32 hash = 0;

    // 将前4个字节转换为整型
    QDataStream stream(&byteArray, QIODevice::ReadOnly);
    stream >> hash;

    return hash;
}

在上面的代码中,我们使用了Qt提供的QCryptographicHash类,使用MD5哈希算法将字符串转换为固定长度的字节数组。然后,我们将前4个字节转换为一个无符号32位整数作为唯一的整型值。

使用示例:

QString str = "Hello World";
quint32 uniqueInt = stringToUniqueInt(str);

请注意,尽管上述方法可以将字符串转换为唯一的整型,但并不能保证绝对的唯一性。不同的字符串也可能具有相同的哈希值,这是哈希算法的特性决定的。

你可能感兴趣的:(qt,开发语言)