diff options
author | Federico Guerinoni <guerinoni@micro-systems.it> | 2019-12-06 22:41:36 +0100 |
---|---|---|
committer | Thiago Macieira <thiago.macieira@intel.com> | 2019-12-20 06:09:27 +0000 |
commit | a0eb51c3870d90c06966dbfbe26b114f39103b60 (patch) | |
tree | 7c0ef5a450534a68835319da26c8e9eb2449690d /src/corelib/tools/qbitarray.cpp | |
parent | 62c3dd5632b04a7ee2410cc2233c0d0605ad5bd6 (diff) |
QBitArray: Add method to get int value
It is useful to use an array of bit as an integer value.
I add also a prarameter to set endianness when converting
value to UInt32.
[ChangeLog][QtCore][QBitArray] Added toUInt32() to return
the bit array's value as a uint32_t.
Change-Id: I9d8c7a33f11e7ce94cb67aa9a50b11fa42d56168
Reviewed-by: Thiago Macieira <thiago.macieira@intel.com>
Diffstat (limited to 'src/corelib/tools/qbitarray.cpp')
-rw-r--r-- | src/corelib/tools/qbitarray.cpp | 34 |
1 files changed, 34 insertions, 0 deletions
diff --git a/src/corelib/tools/qbitarray.cpp b/src/corelib/tools/qbitarray.cpp index f0b81cce66..4db0f61599 100644 --- a/src/corelib/tools/qbitarray.cpp +++ b/src/corelib/tools/qbitarray.cpp @@ -342,6 +342,40 @@ QBitArray QBitArray::fromBits(const char *data, qsizetype size) return result; } +/*! + \since 5.13 + + Returns the array of bit converted to an int. The conversion is based of endianness value. + Converts up to the first 32 bits of the array to \c uint32_t and returns it, + obeying \a endianness. If the array has more than 32 bits, \a ok is set to false + and this function returns zero; otherwise, it's set to true. +*/ +quint32 QBitArray::toUInt32(QSysInfo::Endian endianness, bool *ok) const noexcept +{ + if (size() > 32) { + if (ok != nullptr) { + *ok = false; + } + + return 0; + } + + if (ok != nullptr) { + *ok = true; + } + + auto factor = 1; + quint32 total = 0; + for (auto i = 0; i < size(); ++i, factor *= 2) { + const auto index = endianness == QSysInfo::Endian::LittleEndian ? i : (size() - i - 1); + if (testBit(index)) { + total += factor; + } + } + + return total; +} + /*! \fn bool QBitArray::isDetached() const \internal |