Search code examples
c++c++14constexprstd-bitset

Bit reversal for N bit word using c++ constexpr


I am working on a bit reversal algorithm for an fft implementation, my implementation so far is

//assume the proper includes

template<unsigned long bits>
unsigned long&& bitreverse(unsigned long value){
    std::bitset<bits> input(value);
    std::bitset<bits> result;
    unsigned long j=input.size()-1;
    for (unsigned long i=0; i<input.size(); ++i) {
        result[i]=input[j];
        j--;
    }
    return std::move(result.to_ulong());
}

I need to be able to reverse the bits in an N bit word. My current implementation is functional but I would like to re-write it so that the result can be used as a constexpr, the function signature would need to be either:

template<unsigned long bits>
constexpr unsigned long&& bitreverse(unsigned long value);

or:

template<unsigned long bits,unsigned long value>
constexpr unsigned long&& bitreverse();

or something close...

I'm not sure how to begin implementing this.

I would like to avoid bitwise operations if possible, but i'm not opposed to them.

Thanks


Solution

  • You could just do this:

    template <unsigned long bits>
    constexpr unsigned long bitreverse(unsigned long value) {
        unsigned long result = 0;
        for (std::size_t i = 0, j = bits - 1; i < bits; ++i, --j) {
            result |= ((value & (1 << j)) >> j) << i;
        }
        return result;
    }
    

    I'm not sure why you want to use an r-value reference for the return type. It's not going to make anything more efficient, and I think will result in a dangling reference.