Skip to content

Instantly share code, notes, and snippets.

@bit-hack
Created January 3, 2018 17:33
Show Gist options
  • Save bit-hack/729bfb731bc4093a5d7621631166d050 to your computer and use it in GitHub Desktop.
Save bit-hack/729bfb731bc4093a5d7621631166d050 to your computer and use it in GitHub Desktop.
Helpers for getting and setting bit ranges
#include <cstdint>
namespace {
template <int hi, int lo>
constexpr uint32_t mask() {
// hi_mask xor lo_mask
return ((1u << hi) | ((1u << hi) - 1u)) ^ ((1u << lo) - 1u);
}
template <int hi, int lo>
void set(uint32_t &out, const uint32_t in) {
out &= ~mask<hi, lo>();
out |= (in << lo) & mask<hi, lo>();
}
template <int hi, int lo>
void get(const uint32_t in, uint32_t &out) {
out = (in & mask<hi, lo>()) >> lo;
}
} // namespace {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment