最快的函数,用于在无符号整数中将位设置为1

Vin*_*ent 7 c++ optimization bit-manipulation bitmask c++11

我有一个在超级计算机上进行模拟的算法,需要使用大量的位操作.有些操作需要掩码,特别是这样的函数:

template <typename Type,
          class = typename std::enable_if<std::is_integral<Type>::value>::type,
          class = typename std::enable_if<std::is_unsigned<Type>::value>::type>
inline Type mask(const std::size_t first, const std::size_t last)
{
     // Something
}
Run Code Online (Sandbox Code Playgroud)

这将生成一个类型的掩码,Type其中范围中的位[first, last[被设置为1(first并且last是运行时变量)

例如:

mask<unsigned char>(3, 6) -> 00111000
Run Code Online (Sandbox Code Playgroud)

我将需要数千亿这些掩码,所以我需要尽可能优化这个功能(但在普通的标准C++ 11中).怎么做 ?

Mar*_*som 8

return (1 << last) - (1 << first);
Run Code Online (Sandbox Code Playgroud)