Suppose I have a ushort value that I would like to set bits from 1 to 4 inclusive (assuming 0 is LSB and 15 is MSB).
In C ++, you can define a structure that maps specific bits:
struct KibblesNBits
{
unsigned short int TheStart: 1;
unsigned short int TheMeat: 4;
unsigned short int TheRest: 11;
}
Then you can directly set the value to "TheMeat". I want to do something like this in C #. Ideally, I would like the funcion definition to look like this:
public ModValue SetRange<ModValue, RangeValue>(ModValue valueToMod, int startIndex, int endIndex, RangeValue rangeValueToAssign)
It would also be necessary to evaluate that rangeValueToAssign does not exceed the maximum size (provided that the unsigned values are from 0 to max). Therefore, if the range is from 1 to 4, it is 4 bits, the range will be from 0 to 15. If it goes beyond these limits, throw an exception.
BitConverter, - . , . ?
: :
public static ushort SetRange(ushort valueToMod, int startIndex, int endIndex, ushort rangeValueToAssign)
{
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");
ushort value_to_add = (ushort)(rangeValueToAssign << startIndex);
return (ushort)(valueToMod + value_to_add);
}
:
ushort new_val = SetRange(120, 1, 2, 3);
"new_val" 126.