How to efficiently de-interleave bits (inverse Morton)

后端 未结 5 1081
情歌与酒
情歌与酒 2020-12-05 03:15

This question: How to de-interleave bits (UnMortonizing?) has a good answer for extracting one of the two halves of a Morton number (just the odd bits), but I need a solutio

5条回答
  •  情书的邮戳
    2020-12-05 03:47

    Code for the Intel Haswell and later CPUs. You can use the BMI2 instruction set which contains the pext and pdep instructions. These can (among other great things) be used to build your functions.

    #include 
    #include 
    
    // on GCC, compile with option -mbmi2, requires Haswell or better.
    
    uint64_t xy_to_morton (uint32_t x, uint32_t y)
    {
        return _pdep_u32(x, 0x55555555) | _pdep_u32(y,0xaaaaaaaa);
    }
    
    uint64_t morton_to_xy (uint64_t m, uint32_t *x, uint32_t *y)
    {
        *x = _pext_u64(m, 0x5555555555555555);
        *y = _pext_u64(m, 0xaaaaaaaaaaaaaaaa);
    }
    

提交回复
热议问题