Last active
June 12, 2019 17:38
-
-
Save Leedehai/8e633eed0a6e3545dbea718e5ed920b4 to your computer and use it in GitHub Desktop.
Make 64 bit masks: set bits [a, b] to 1's and others 0's
This file contains 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
// C++ version 1 | |
#include <iostream> | |
#include <string> | |
#include <bitset> | |
using namespace std; // yeah I know it's better to use "ns::foo" instead of declaring "using namespace ns" at the top... | |
// but this file is just a toy, right. Live a little. | |
int main_old() | |
{ | |
int a = 31, b = 63; | |
uint64_t mask = (((uint64_t) -1 >> ((uint64_t)63 - (b))) & ~(((uint64_t)1 << (a)) - 1)); | |
bitset<64> maskbits(mask); | |
cout << maskbits.to_string() << endl; | |
} | |
// C++ version 2 | |
#include <iostream> | |
#include <string> | |
#include <bitset> | |
using namespace std; | |
/** | |
* Class templates: UnsignedIntTypeSelector | |
* Usage: typename UnsignedIntTypeSelector<64>::type fooReturnUint64(); <=> uint64_t fooReturnUint64(); | |
* --------------------------- | |
* Select uint*_t based on number of bits. | |
*/ | |
template <unsigned short> struct UnsignedIntTypeSelector; | |
template <> struct UnsignedIntTypeSelector<64> { typedef uint64_t type; }; | |
template <> struct UnsignedIntTypeSelector<32> { typedef uint32_t type; }; | |
template <> struct UnsignedIntTypeSelector<16> { typedef uint16_t type; }; | |
template <> struct UnsignedIntTypeSelector<8> { typedef uint8_t type; }; | |
/** | |
* Function template: getBitMask<>() | |
* Usage: uint64_t mask = getBitMask<64>(60, 63) => 111100..0 (high bits 63~60 set to 1). | |
* --------------------------- | |
* Set bits [lo, hi] to 1's and others 0's, as long as 0 <= lo <= hi <= (NUM_BITS - 1). | |
*/ | |
template <unsigned short NUM_BITS> | |
constexpr typename UnsignedIntTypeSelector<NUM_BITS>::type getBitMask(uint64_t lo, uint64_t hi) { | |
typedef typename UnsignedIntTypeSelector<NUM_BITS>::type return_type; | |
return ((return_type) -1 >> ((return_type)NUM_BITS - 1 - (hi))) & ~(((return_type)1 << (lo)) - 1); | |
} | |
int main() | |
{ | |
uint8_t mask = getBitMask<8>(3, 5); | |
bitset<8> maskbits(mask); | |
cout << maskbits.to_string() << endl; // print "00111000" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment