Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to produce a mask with n ones starting at position i

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?

like image 830
Vincent Avatar asked Sep 04 '16 21:09

Vincent


People also ask

How do you make a mask of all ones?

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.

How do you mask in C++?

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.

How do you mask the least significant bit?

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 .


1 Answers

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;
}
like image 117
KIIV Avatar answered Oct 27 '22 08:10

KIIV