private static long Read8Bit(ReadBuffer readBuffer, int length, bool isSigned)
{
if (length <= 0)
{
throw new EmberException("Unexpected zero length for integer.");
}
var position = readBuffer.Position;
var mostSignificant = readBuffer[readBuffer.Index++];
long result;
long leading;
// - 1 accounts for the fact that we must not overwrite the sign bit by shifting in bits
const int MostSignificantShift = Constants.BitsPerLong - Constants.BitsPerByte - 1;
if (isSigned && ((mostSignificant & 0x80) != 0))
{
result = (Constants.AllBitsSetLong << Constants.BitsPerByte) | mostSignificant;
leading = Constants.AllBitsSetLong << MostSignificantShift;
}
else
{
result = mostSignificant;
leading = 0x00;
}
for (--length; length > 0; --length)
{
const long DiscardBitsMask = Constants.AllBitsSetLong << MostSignificantShift;
if ((result & DiscardBitsMask) != leading)
{
throw CreateEmberException(
"The integer, length or exponent at position {0} exceeds the expected range.", position);
}
result <<= Constants.BitsPerByte;
result |= readBuffer[readBuffer.Index++];
}
return result;
}