From 296ce314a3863becc612f90f3253c9f5501def47 Mon Sep 17 00:00:00 2001 From: John Ralls Date: Mon, 17 Nov 2014 14:43:23 -0800 Subject: [PATCH] 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. --- src/libqof/qof/qofint128.cpp | 29 ++++++++++++----------------- src/libqof/qof/qofint128.hpp | 5 +++++ 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/src/libqof/qof/qofint128.cpp b/src/libqof/qof/qofint128.cpp index 08069febac..544b1db976 100644 --- a/src/libqof/qof/qofint128.cpp +++ b/src/libqof/qof/qofint128.cpp @@ -163,6 +163,16 @@ QofInt128::abs() const noexcept return *this; } +uint +QofInt128::bits() const noexcept +{ + uint bits {static_cast(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::operator-() const noexcept @@ -305,23 +315,8 @@ QofInt128::operator*= (const QofInt128& b) noexcept m_flags |= overflow; return *this; } - uint abits {}, bbits {}; - uint64_t temp {m_lo}; - 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); + + uint abits {bits()}, bbits {b.bits()}; if (abits + bbits > maxbits) { m_flags |= overflow; diff --git a/src/libqof/qof/qofint128.hpp b/src/libqof/qof/qofint128.hpp index c160da2320..6704ce3a7d 100644 --- a/src/libqof/qof/qofint128.hpp +++ b/src/libqof/qof/qofint128.hpp @@ -179,6 +179,11 @@ enum // Values for m_flags */ 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 * the QofInt128 is overflowed or NaN it will contain the words "Overflow" or