Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
    }
like image 786
Pedro77 Avatar asked Feb 03 '26 03:02

Pedro77


1 Answers

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.

like image 113
Edwin de Koning Avatar answered Feb 04 '26 16:02

Edwin de Koning



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!