Lets say I have a ushort value that I would like to set bits 1 to 4 inclusive (assuming 0 is the LSB and 15 is the MSB).
In C++ you could define a struct that mapped out specific bits:
struct KibblesNBits
{
unsigned short int TheStart: 1;
unsigned short int TheMeat: 4;
unsigned short int TheRest: 11;
}
Then you could assign a value to 'TheMeat' directly. I'm looking to do something similar in C#. Ideally, I would like a funcion definition that looked like this:
public ModValue SetRange<ModValue, RangeValue>(ModValue valueToMod, int startIndex, int endIndex, RangeValue rangeValueToAssign)
It would also need to valide that the rangeValueToAssign does not exceed the maximum size (assuming values are unsigned from 0 to max). So if the range is from 1 to 4, this is 4 bits, range would be from 0 to 15. If it is outside these limits, throw an exception.
I didnt find anything in the BitConverter class that could do something like this. Best I could think of was using manaul shift operators. Is there a better way to do this?
Edit: A non generic version might look something like this:
public static ushort SetRange(ushort valueToMod, int startIndex, int endIndex, ushort rangeValueToAssign)
{
// Determine max value
ushort max_value = Convert.ToUInt16(Math.Pow(2.0, (endIndex - startIndex) + 1.0) - 1);
if(rangeValueToAssign > max_value) throw new Exception("Value To Large For Range");
// Shift the value and add it to the orignal (effect of setting range?)
ushort value_to_add = (ushort)(rangeValueToAssign << startIndex);
return (ushort)(valueToMod + value_to_add);
}
Where:
ushort new_val = SetRange(120, 1, 2, 3);
would result in 'new_val' being set to 126.