在字节中设置一些连续的位

Oha*_*der 2 c# byte bit-manipulation bit

我需要一种具有以下签名的有效方法:

public byte SetBits(byte oldValue, byte newValue, int startBit, int bitCount)
Run Code Online (Sandbox Code Playgroud)

它返回oldValue,只有从其startbit位开始到其startbit + bitcount位(从零开始)的位,才被替换bitcountnewValue

例如,如果:

  • oldValue = 11101101
  • newValue = 10000011
  • startBit = 1
  • bitCount = 2

那么结果将是:11101111(分段10oldValue被替换为对应11于段newValue

dee*_*ee1 5

在这里,您可以...双向移动掩码以获取掩码...然后使用它生成新字节

public static byte SetBits(byte oldValue, byte newValue, int startBit, int bitCount)
{
    if (startBit < 0 || startBit > 7 || bitCount < 0 || bitCount > 7 
                     || startBit + bitCount > 8)
        throw new OverflowException();

    int mask = (255 >> 8 - bitCount) << startBit;
    return Convert.ToByte((oldValue & (~mask)) | ((newValue << startBit) & mask));
}
Run Code Online (Sandbox Code Playgroud)