'Update value while using byte offset and width numerically

I have some value n register and I have to update it, but I have to take into consideration byte offset and byte width which can vary (user provided)

I believe I managed to do it, but just on strings and I have no idea how to do it mathematically/bitwise

var value = 534543;
var binaryCurrentValue = Convert.ToString(value, 2);

var newValue = 10654;
var binaryNewValue = Convert.ToString(newValue, 2);

Console.WriteLine(value);
Console.WriteLine(binaryCurrentValue);
Console.WriteLine("__________");
Console.WriteLine(newValue);
Console.WriteLine(binaryNewValue);
Console.WriteLine("__________");

var byteOffset = 1;
var byteWidth = 2;
var partAfterByteOffsetAndWidth = string.Join("", binaryCurrentValue.Skip(byteOffset * 8).Take(byteWidth * 8));

Console.WriteLine("width and offset applied to original value:");
Console.WriteLine(partAfterByteOffsetAndWidth);
Console.WriteLine("result:");
Console.WriteLine(binaryNewValue + partAfterByteOffsetAndWidth);

The outcome:

534543
10000010100000001111
__________
10654
10100110011110
__________
width and offset applied to original value:
100000001111
result:
10100110011110100000001111

Any tips? thanks in advance



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source