Remove rightmost set bit
suggest changeC-style bit-manipulation
template <typename T>
T rightmostSetBitRemoved(T n)
{
// static_assert(std::is_integral<T>::value && !std::is_signed<T>::value, "type should be unsigned"); // For c++11 and later
return n & (n - 1);
}
Explanation
- if
nis an unsigned zero,n - 1wraps andn & (n - 1)is zero. The bit pattern below assumes that unsigned value. A signed negative operand, or a signed overflow ofn - 1, is not that pattern. Signed overflow is undefined behavior. - else
ncan be written0bxxxxxx10..00andn - 1is0bxxxxxx011..11, son & (n - 1)is0bxxxxxx000..00.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents