What is the fastest way (in terms of cpu cycles on common modern architecture), to produce a mask with len
bits set to 1 starting at position pos
:
template <class UIntType>
constexpr T make_mask(std::size_t pos, std::size_t len)
{
// Body of the function
}
// Call of the function
auto mask = make_mask<uint32_t>(4, 10);
// mask = 00000000 00000000 00111111 11110000
// (in binary with MSB on the left and LSB on the right)
Plus, is there any compiler intrinsics or BMI function that can help?
A C language shortcut for creating a mask with all 1s and a zero in bit 6 would be: readMask = ~(1 << 6); The value 0b1000000 gets created in the parentheses. Then, the bitwise NOT operator ~ is applied, making the result 0b0111111.
The element of the mask can be either set or not set (i.e. 0 or 1). This denotes the availability of the chosen element in the bitmask. For example, an element i is available in the subset if the ith bit of mask is set. For the N element set, there can be a 2N mask each corresponding to a subset.
The usual way is to take a 1 , and shift it left n bits. That will give you something like: 00100000 . Then subtract one from that, which will clear the bit that's set, and set all the less significant bits, so in this case we'd get: 00011111 . A mask is normally used with bitwise operations, especially and .
Fastest way? I'd use something like this:
template <class T>
constexpr T make_mask(std::size_t pos, std::size_t len)
{
return ((static_cast<T>(1) << len)-1) << pos;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With