For sake of experiment lets have a function that takes in a bitmask and offset and returns the mask shifted by offset. What would be a performance friendly way to determine if the operation will not shift any parts of the bitmask past the width of the data type? This is what I've tried so far, but maybe there is more optimal way to check this?
Example program: (Note: I'm looking for a solution for all data types, not only 16 bit integers)
#include <iostream>
using namespace std;
uint16_t TestFunc(uint16_t offset, uint16_t mask)
{
if (offset >= sizeof(uint16_t) * 8)
throw std::exception("Offset outside bounds");
// find the index of the left-most bit in the mask
int16_t maskLeftBitIndex = 0;
uint16_t maskCopy = mask;
while (maskCopy >>= 1)
maskLeftBitIndex++;
// check if the said left-most bit will be shifted past the width of uint16_t
if (offset + maskLeftBitIndex >= sizeof(uint16_t) * 8)
throw std::exception("Mask will end up outside bounds");
return mask << offset;
}
int main()
{
try
{
uint16_t test = TestFunc(15, 2);
cout << "Bitmask value: " << test;
}
catch (std::exception& e)
{
cout << "Exception encountered: " << e.what();
}
return 0;
}