bitwise: add 'from_bits' integer extraction
constructs an integer from range of indices over a bitfield
This commit is contained in:
parent
68faa8838e
commit
7708b12c37
29
bitwise.hpp
29
bitwise.hpp
@ -11,11 +11,14 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*
|
||||
* Copyright 2011 Danny Robson <danny@nerdcruft.net>
|
||||
* Copyright 2011-2018 Danny Robson <danny@nerdcruft.net>
|
||||
*/
|
||||
|
||||
#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 <type_traits>
|
||||
#include <cstdint>
|
||||
@ -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 <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
|
||||
|
Loading…
Reference in New Issue
Block a user