bitwise: add 'from_bits' integer extraction

constructs an integer from range of indices over a bitfield
This commit is contained in:
Danny Robson 2018-03-20 13:34:19 +11:00
parent 68faa8838e
commit 7708b12c37

View File

@ -11,11 +11,14 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
* *
* Copyright 2011 Danny Robson <danny@nerdcruft.net> * Copyright 2011-2018 Danny Robson <danny@nerdcruft.net>
*/ */
#ifndef __UTIL_BITWISE_HPP #ifndef CRUFT_UTIL_BITWISE_HPP
#define __UTIL_BITWISE_HPP #define CRUFT_UTIL_BITWISE_HPP
#include "types/bits.hpp"
#include "debug.hpp"
#include <type_traits> #include <type_traits>
#include <cstdint> #include <cstdint>
@ -87,6 +90,26 @@ namespace util {
{ {
return __builtin_popcount (t); return __builtin_popcount (t);
} }
///////////////////////////////////////////////////////////////////////////
/// returns the integral value composed of the bits from `val' in the
/// inclusive range [lo, hi].
template <typename ValueT, typename IndexT>
constexpr ValueT
from_bits (ValueT val, IndexT hi, IndexT lo)
{
CHECK_LT (hi, IndexT (sizeof (ValueT) * 8));
CHECK_LT (lo, IndexT (sizeof (ValueT) * 8));
CHECK_GE (hi, 0);
CHECK_GE (lo, 1);
CHECK_GE (hi, lo);
ValueT zero = 0;
ValueT ones = ~zero;
return (val >> lo) & (ones >> (sizeof (ValueT) * 8 - (hi - lo + 1)));
}
} }
#endif #endif