From fffbdb4c374333c6660ef2265f636edbd2903b87 Mon Sep 17 00:00:00 2001 From: Thiago Macieira Date: Tue, 13 Jun 2017 10:58:04 -0700 Subject: Doc: add a note about QRandomGenerator returning the sign bit set Found this in a few uses of qrand() that assumed the result would be non-negative. Change-Id: Ia53158e207a94bf49489fffd14c7c029515cf42c Reviewed-by: Lars Knoll --- src/corelib/global/qrandom.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) (limited to 'src/corelib/global/qrandom.cpp') diff --git a/src/corelib/global/qrandom.cpp b/src/corelib/global/qrandom.cpp index 6a92260c46..66f21bc7f0 100644 --- a/src/corelib/global/qrandom.cpp +++ b/src/corelib/global/qrandom.cpp @@ -802,6 +802,15 @@ static Q_NEVER_INLINE void fill(void *buffer, void *bufferEnd) /*! Generates one 32-bit random value and returns it. + Note about casting to a signed integer: all bits returned by this function + are random, so there's a 50% chance that the most significant bit will be + set. If you wish to cast the returned value to int and keep it positive, + you should mask the sign bit off: + + \code + int value = QRandomGenerator::get32() & std::numeric_limits::max(); + \endcode + \sa get64(), getReal() */ quint32 QRandomGenerator::get32() @@ -814,6 +823,15 @@ quint32 QRandomGenerator::get32() /*! Generates one 64-bit random value and returns it. + Note about casting to a signed integer: all bits returned by this function + are random, so there's a 50% chance that the most significant bit will be + set. If you wish to cast the returned value to qint64 and keep it positive, + you should mask the sign bit off: + + \code + qint64 value = QRandomGenerator::get64() & std::numeric_limits::max(); + \endcode + \sa get32(), getReal(), QRandomGenerator64 */ quint64 QRandomGenerator::get64() -- cgit v1.2.3