Translate and explain some C++ bit operations to C#
Can you help me with the translation to c# of this 3rd part API method:
I also didnt understand everything that is happening at the bit operations..
inline void SetBits(unsigned long& aValue,unsigned int aData,unsigned int aPosition,unsigned int aLength)
{
unsigned int datamask; // data mask, before aPosition shift
if (aLength == 32)
datamask = 0xFFFFFFFF;
else
datamask = (1L << aLength) - 1;
aValue &= ~(datamask << aPosition); // Clear bits
aValue |= (aData & datamask) << aPosition; // Set value
}
Im getting this error in C# version:
Error Operator '<<' cannot be applied to operands of type 'long' and 'uint'
Error Operator '<<' cannot be applied to operands of type 'uint' and 'uint'
EDITED:
I think this solution is ok:
private void SetBits(ref uint value, uint data开发者_运维问答, int position, int length)
{
uint datamask; // data mask, before position shift
if (length >= 32)
datamask = 0xFFFFFFFF;
else
datamask = ((uint)1 << length) - 1;
value &= ~(datamask << position); // Clear bits
value |= (data & datamask) << position; // Set value
}
The count part of a shift operation in C# should always be an int. So try making aLength and aPosition into an int instead of a uint. See here.
As an example to explain the code (in 8-bit, for the sake of simplicity), lets say aValue = 01101001
, aData = 00100110
, aPosition = 3
and aLength = 4
:
datamask = (1L << aLength) - 1;
creates a mask with the aLength
(4) rightmost bits set to one: datamask = 00001111
.
aValue &= ~(datamask << aPosition);
clears the aLength
(4) bits at the aPosition
th (3rd) bit position: aValue = 01101001 & 10000111 = 00000001
.
aValue |= (aData & datamask) << aPosition;
now copies the aLength
(4) rightmost bits of aData
to the aPosition
th (3rd) bit position in aValue
: aValue = 00000001 | 00110000 = 00110001
.
So what this function does, is replace the aLength
bits at the aPosition
th bit position in aValue
with the aLength
rightmost bits in aData
.
I didnt understand what happens here:
datamask = (1L << aLength) - 1;
This code creates a mask with the first (right-most) aLength
bits set to 1. The code uses a special rule for aLength=32 because this formula would overflow.
精彩评论