This question is a follow up of Calculate min/max values for signed or unsigned integral number with any valid number of bits (up to 64)
I was answering the question Given two int values, return the one closer to 10, and I indicated that something like the following snippet of code could be a different approach for solving the problem.
In the original question, it turned out I had made a mistake, but since there were already some answers, I've decided to post a follow up question with the fixes.
Can this be done in a more efficient or more elegant way?
public class Bits
{
public static void MinMaxI(ulong _bits, out long _min, out long _max)
{
// ? unsigned range with at least one value bit
if (_bits < 2 || _bits > 64)
{
throw new System.ArgumentOutOfRangeException("_bits", _bits,
String.Format("2 <= _bits <= 64"));
}
_min = ~(long)0 << (int)(_bits - 1);
_max = -1 - _min;
}
public static long MinI(ulong _bits)
{
// ? unsigned range with at least one value bit
if (_bits < 2 || _bits > 64)
{
throw new System.ArgumentOutOfRangeException("_bits", _bits,
String.Format("2 <= _bits <= 64"));
}
return ~(long)0 << (int)(_bits - 1);
}
public static long MaxI(ulong _bits)
{
// ? unsigned range with at least one value bit
if (_bits < 2 || _bits > 64)
{
throw new System.ArgumentOutOfRangeException("_bits", _bits,
String.Format("2 <= _bits <= 64"));
}
return -1 - (~(long)0 << (int)(_bits - 1));
}
public static ulong MaxN(ulong _bits)
{
// ? unsigned range with at least one value bit
if (_bits < 1 || _bits > 64)
{
throw new System.ArgumentOutOfRangeException("_bits", _bits,
String.Format("1 <= _bits <= 64"));
}
return _bits == 64 ? ~(ulong)0 : ~(~(ulong)0 << (int)_bits);
}
}