enum class bytePos
{
LOW_BYTE,
HIGH_BYTE
};
auto selectMultipleBits16(uint16_t uiInput, uint8_t uiStartBit, uint8_t uiEndBit) -> uint16_t;
auto bitRangeCheck(uint8_t uiSize, byte byBitPos) -> bool;
auto byteSelect16(bytePos pos, uint16_t uiInput) -> uint8_t;
uint16_t uiTest = 0xE4;
void setup()
{
Serial.begin(9600);
uint16_t uiResult = selectMultipleBits16(uiTest, 0, 6);
Serial.println("Result: " + String(uiResult));
uiResult = selectMultipleBits16(static_cast<uint16_t>(byteSelect16(bytePos::HIGH_BYTE,uiTest)),0,6);
Serial.println("Result: " + String(uiResult));
}
void loop() {
// put your main code here, to run repeatedly:
}
auto selectMultipleBits16(uint16_t uiInput, uint8_t uiStartBit, uint8_t uiEndBit) -> uint16_t
{
if(!bitRangeCheck(sizeof(uiInput), uiStartBit) || !bitRangeCheck(sizeof(uiInput), uiEndBit))
{
Serial.println("Error: Bitposition is out of range!");
return 0;
}
else
{
// Erstelle eine Maske, die die Bits von uiStartBit bis uiEndBit auf 1 setzt
uint16_t mask = ((1U << (uiEndBit - uiStartBit + 1)) - 1) << uiStartBit;
// Wende die Maske an und verschiebe die Bits an den Anfang
uint16_t uiOutput = (uiInput & mask) >> uiStartBit;
return uiOutput;
}
}
// checking whether the passed bitPosition is out of range of the variable
auto bitRangeCheck(uint8_t uiSize, byte byBitPos) -> bool
{
switch (uiSize)
{
case 1:
if (byBitPos > 7)
return false;
else
return true;
break;
// uint16 or int16
case 2:
if (byBitPos > 15)
return false;
else
return true;
break;
// uint32 or int32
case 4:
if (byBitPos > 31)
return false;
else
return true;
break;
// uint64 or int64
case 8:
if (byBitPos > 63)
return false;
else
return true;
break;
// uint8 or int8
default:
Serial.println("This Size is not programmed to check: " + String(uiSize));
break;
}
}
auto byteSelect16(bytePos pos, uint16_t uiInput) -> uint8_t
{
switch (pos)
{
case bytePos::LOW_BYTE:
return uiInput & 0xFF;
break;
case bytePos::HIGH_BYTE:
return (uiInput >> 8) & 0xFF;
break;
default:
return 0xFF;
break;
}
}