set some consecutive bits in a byte
I need an efficient method with the following signature:
public byte SetBits(byte oldValue, byte newValue, int startBit, int bitCount)
Which returns oldValue
, only that starting from its startbit
bit 开发者_运维问答up to its startbit + bitcount
bit (zero-based), it's replaced with the first bitcount
bits of newValue
For example, if:
oldValue = 11101101
newValue = 10000011
startBit = 1
bitCount = 2
Then the result would be: 11101111
(the segment 10
in oldValue
is replaced with the corresponding 11
segment in newValue
)
Here you go... Bitshift both directions to get the mask... then use it to generate the new byte
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));
}
startBit--; //account for 0 indexing
byte flag = 1 << startBit;
for (int i = startBit; i < bitCount; i++, flag <<= 1)
{
byte mask = newValue & flag;
if (mask != 0)
oldValue |= mask;
else
oldValue &= ~(flag);
}
return oldValue;
Some brain compiled code here but it should be along the lines that you want if I read the question correctly.
If I understood your question, I think this is what you are after:
byte mask = 0xFF;
for (int i = startPos-1; i < numBits; i++)
{
if ((newValue & (1 << i)) == 1)
{
mask = (byte)(mask | (1 << i));
}
else
{
mask = (byte)(mask &~(1<<i));
}
}
return (byte)(oldValue & mask);
This code is based on some neat tricks from Low Level Bit Hacks You Absolutely Must Know
I know setting a bit in a byte initialized to 0xFF is really a no-op, but I felt the code should be left in as it can help show off what is really going on. I encourage users of the code to optimize it as needed.
精彩评论