DEV Community

Discussion on: Daily Challenge #255 - Is There an Odd Bit?

Collapse
 
mpixel profile image
Max Pixel • Edited

This C++ solution supports a number of any size (byte, 16-bit, 32-bit, etc), and compiles down to just a single CPU instruction for every invocation of any_odd.

constexpr unsigned long long odd_bits{0b1010101010101010101010101010101010101010101010101010101010101010ull};
template<typename T>
inline bool any_odd(const T& test)
{
    static_assert(std::is_integral<T>::value, "any_odd only works with integers");
    return (*reinterpret_cast<const T*>(&odd_bits) & test) != 0;
}

Note that without the reinterpret_cast, an unnecessary cdqe instruction will likely be introduced, even with maximum optimization turned on.