Standard C++11 code equivalent to the PEXT Haswell instruction (and likely to be optimized by compiler)

前端 未结 1 1033
遇见更好的自我
遇见更好的自我 2021-01-12 08:19

The Haswell architectures comes up with several new instructions. One of them is PEXT (parallel bits extract) whose functionality is explained by this image (so

相关标签:
1条回答
  • 2021-01-12 08:36

    Here is some code from Matthew Fioravante's stdcxx-bitops GitHub repo that was floated to the std-proposals mailinglist as a preliminary proposal to add a constexpr bitwise operations library for C++.

    #ifndef HAS_CXX14_CONSTEXPR
    #define HAS_CXX14_CONSTEXPR 0
    #endif
    
    #if HAS_CXX14_CONSTEXPR
    #define constexpr14 constexpr
    #else
    #define constexpr14
    #endif
    
    //Parallel Bits Extract
    //x    HGFEDCBA
    //mask 01100100
    //res  00000GFC
    //x86_64 BMI2: PEXT
    template <typename Integral>
    constexpr14 Integral extract_bits(Integral x, Integral mask) {
      Integral res = 0;
      for(Integral bb = 1; mask != 0; bb += bb) {
        if(x & mask & -mask) {
          res |= bb;
        }
        mask &= (mask - 1);
      }
      return res;
    }
    
    0 讨论(0)
提交回复
热议问题