diff --git a/bitwise.hpp b/bitwise.hpp index 0743cb45..3e76f76e 100644 --- a/bitwise.hpp +++ b/bitwise.hpp @@ -11,11 +11,14 @@ * See the License for the specific language governing permissions and * limitations under the License. * - * Copyright 2011 Danny Robson + * Copyright 2011-2018 Danny Robson */ -#ifndef __UTIL_BITWISE_HPP -#define __UTIL_BITWISE_HPP +#ifndef CRUFT_UTIL_BITWISE_HPP +#define CRUFT_UTIL_BITWISE_HPP + +#include "types/bits.hpp" +#include "debug.hpp" #include #include @@ -87,6 +90,26 @@ namespace util { { return __builtin_popcount (t); } + + + /////////////////////////////////////////////////////////////////////////// + /// returns the integral value composed of the bits from `val' in the + /// inclusive range [lo, hi]. + template + 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