Extract a class function bits() to return a size value.

Helps to pre-determine overflow. Also correct the original implementation
in operator *=, which got the wrong answer.
This commit is contained in:
John Ralls 2014-11-17 14:43:23 -08:00
parent 1b288df20d
commit 296ce314a3
2 changed files with 17 additions and 17 deletions

View File

@ -163,6 +163,16 @@ QofInt128::abs() const noexcept
return *this; return *this;
} }
uint
QofInt128::bits() const noexcept
{
uint bits {static_cast<uint>(m_hi == 0 ? 0 : 64)};
uint64_t temp {(m_hi == 0 ? m_lo : m_hi)};
for (;temp > 0; temp >>= 1)
++bits;
return bits;
}
QofInt128 QofInt128
QofInt128::operator-() const noexcept QofInt128::operator-() const noexcept
@ -305,23 +315,8 @@ QofInt128::operator*= (const QofInt128& b) noexcept
m_flags |= overflow; m_flags |= overflow;
return *this; return *this;
} }
uint abits {}, bbits {};
uint64_t temp {m_lo}; uint abits {bits()}, bbits {b.bits()};
do
++abits;
while (temp >>= 1);
temp = m_hi;
do
++abits;
while (temp >>= 1);
temp = b.m_lo;
do
++bbits;
while (temp >>= 1);
temp = b.m_hi;
do
++bbits;
while (temp >>= 1);
if (abits + bbits > maxbits) if (abits + bbits > maxbits)
{ {
m_flags |= overflow; m_flags |= overflow;

View File

@ -179,6 +179,11 @@ enum // Values for m_flags
*/ */
bool isZero() const noexcept; bool isZero() const noexcept;
/**
* @return the number of bits used to represent the value
*/
uint bits() const noexcept;
/** /**
* Fills a supplied buffer with a representation of the number in base 10. If * Fills a supplied buffer with a representation of the number in base 10. If
* the QofInt128 is overflowed or NaN it will contain the words "Overflow" or * the QofInt128 is overflowed or NaN it will contain the words "Overflow" or