Position of least significant bit that is set

后端 未结 23 1271
时光取名叫无心
时光取名叫无心 2020-11-22 08:46

I am looking for an efficient way to determine the position of the least significant bit that is set in an integer, e.g. for 0x0FF0 it would be 4.

A trivial impleme

23条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 09:21

    If C++11 is available for you, a compiler sometimes can do the task for you :)

    constexpr std::uint64_t lssb(const std::uint64_t value)
    {
        return !value ? 0 : (value % 2 ? 1 : lssb(value >> 1) + 1);
    }
    

    Result is 1-based index.

提交回复
热议问题