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位(从零开始)的位,才被替换bitcount为newValue
例如,如果:
oldValue = 11101101newValue = 10000011startBit = 1bitCount = 2那么结果将是:11101111(分段10中oldValue被替换为对应11于段newValue)
在这里,您可以...双向移动掩码以获取掩码...然后使用它生成新字节
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)