Search code examples
c++boostbit-manipulationavx512boost-multiprecision

Find First Set instruction (ffs) for boost multiprecision uint512_t


I'm developing an algorithm that uses __builtin_ffsll() with uint64_t type.

I want to switch to 512-bit field using boost multiprecision library (I'm running on a machine with avx512 support).

Is there a similar function as the mentioned builtin? Alternatively, how can I efficiently implement such functionality for 512-bit integers?


Solution

  • From the documentation:

    unsigned lsb(const number-or-expression-template-type& x);

    Returns the (zero-based) index of the least significant bit that is set to 1.

    Throws a std::range_error if the argument is <= 0.

    ffs() is one-based, so adding 1 to lsb()'s return value will make it equivalent. Edit: And as pointed out, taking the case of being passed 0 into account.

    Maybe something like

    unsigned ffs512(const boost::multiprecision::uint512_t &n) {
      if (n.is_zero()) {
        return 0;
      } else {
        return boost::multiprecision::lsb(n) + 1;
      }
    }