0
\$\begingroup\$

The common implementations usually reference: https://github.com/fmatthew5876/stdcxx-bitops/blob/master/include/bitops.hh

I styled my version to match (except for the constexpr macro):

template <typename Integral> constexpr Integral extract_bits(Integral x, Integral mask) { Integral res=0; int bb=1; do { Integral lsb=mask & -mask; mask &= ~lsb; bool isset=x & lsb; res |= isset ? bb : 0; bb+=bb; } while (mask); return res; } template <typename Integral> constexpr Integral deposit_bits(Integral x, Integral mask) { Integral res = 0; int bb=1; do { Integral lsb=mask & -mask; mask &= ~lsb; bool isset=x&bb; res |= (x & bb) ? lsb : 0; bb+=bb; } while(mask); return res; } 
\$\endgroup\$
6
  • \$\begingroup\$ So it looks like you took Matthew Fioravante's version and turned the for-loop in a do-while loop, and the if into a ternary? I'm not really sure this is suitable for Code Review. \$\endgroup\$ Commented Aug 18, 2022 at 20:01
  • \$\begingroup\$ Its the result of quite a bit of optimizing. Take a look at godbolt.org/z/3TqeerMzc \$\endgroup\$ Commented Aug 18, 2022 at 23:25
  • 2
    \$\begingroup\$ Yes, I did see the difference in assembly output, and with your changes it is indeed a bit better. However, if you are not the author of the code you post, it's not considered on-topic for CodeReview.. \$\endgroup\$ Commented Aug 19, 2022 at 5:49
  • \$\begingroup\$ ownership can be discussed here: codereview.meta.stackexchange.com/questions/10829/… \$\endgroup\$ Commented Aug 19, 2022 at 12:46
  • 1
    \$\begingroup\$ I don't see any macro. Did you intend to write "the constexpr keyword" there? \$\endgroup\$ Commented Aug 20, 2022 at 8:31

0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.