Skip to content

Instantly share code, notes, and snippets.

@daniel-j-h
Last active October 13, 2020 19:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daniel-j-h/69736fb5ec147d4212c5 to your computer and use it in GitHub Desktop.
Save daniel-j-h/69736fb5ec147d4212c5 to your computer and use it in GitHub Desktop.
Making use of Haswell's BMI2 PDEP instruction for Morton Codes / Z-Order
#include <cstdint>
#include <immintrin.h>
// Z-order via bit interleaving a and b as in: a[31]b[31]a[30]b[30]...
inline std::uint64_t zorder(std::uint32_t a, std::uint32_t b) {
return _pdep_u64(a, 0xaaaaaaaaaaaaaaaaULL) | _pdep_u64(b, 0x5555555555555555ULL);
}
@daniel-j-h
Copy link
Author

PDEP for zorder encoding, PEXT for zorder decoding:

#include <cstdint>
#include <array>
#include <immintrin.h>

std::uint64_t zorder(const std::array<std::uint32_t, 2> x) {
  return _pdep_u64(x[0], 0xaaaaaaaaaaaaaaaaULL) | _pdep_u64(x[1], 0x5555555555555555ULL);
}

std::array<std::uint32_t, 2> zorder_inv(const std::uint64_t x) {
  return {static_cast<std::uint32_t>(_pext_u64(x, 0xaaaaaaaaaaaaaaaaULL)),
          static_cast<std::uint32_t>(_pext_u64(x, 0x5555555555555555ULL))};
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment