Created
January 3, 2018 17:33
-
-
Save bit-hack/729bfb731bc4093a5d7621631166d050 to your computer and use it in GitHub Desktop.
Helpers for getting and setting bit ranges
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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