View Full Version : Random hex number of given length in QT?
jiveaxe
11th August 2012, 18:35
Hi, I wonder if there is a way using plain QT to obtain a random hexadecimal number of any length. I found that it is possible to get 32 characters hex numbers with QUuid::createUuid() (removing {,},-), but what about for others lengths? I'm missing some qt feature or I have to use simple c++ routines?
Thanks,
Giuseppe
ChrisW67
12th August 2012, 08:11
For simple definitions of "random" you can use qsrand() and then qrand() to get 32, or fewer, bits at a time until you get sufficient bits. If you really want a hexadecimal string then stuff the bytes into a QByteArray and call QByteArray::toHex().
For any cryptographic purpose you want a better source of randomness and a cryptographic PRNG.
BTW: A UUID is not entirely random.
jiveaxe
12th August 2012, 09:05
Ok, I've followed qsrand()/qrand() way:
QTime time = QTime::currentTime();
qsrand((uint)time.msec());
...
QString Utils::getRandomHex(const int &length)
{
QString randomHex;
for(int i = 0; i < length; i++) {
int n = qrand() % 16;
randomHex.append(QString::number(n,16));
}
return randomHex;
}
Powered by vBulletin® Version 4.2.5 Copyright © 2024 vBulletin Solutions Inc. All rights reserved.