1

This code is C++. I can't convert it to C#.

The main problem is !(value & 0xf). I don't know what it does!!

I don't know what operator !(int) does in C++

int GetBitPosition(uint8_t value)
{
    const int i4 = !(value & 0xf) << 2;
    value >>= i4;

    const int i2 = !(value & 0x3) << 1;
    value >>= i2;

    const int i1 = !(value & 0x1);

    const int i0 = (value >> i1) & 1 ? 0 : -8;

    return i4 + i2 + i1 + i0;
}
CorrM
  • 498
  • 6
  • 18

2 Answers2

4

! is the not operator in C++. According to this answer:

Yes. For integral types, ! returns true if the operand is zero, and false otherwise.

So !b here just means b == 0.

In other words, if C# doesn't have an equivalent operator (which I don't understand why it wouldn't), you can, in theory, use the C# equivalent of the following instead:

((value & 0xf) == 0) // parenthesis for readabillity
1
int GetBitPosition(int value)
{
    int i4 = ((value & 0xf) == 0 ? 1 : 0) << 2;
    value >>= i4;

    int i2 = ((value & 0x3) == 0 ? 1 : 0)  << 1;
    value >>= i2;

    int i1 = (value & 0x1) == 0 ? 1 : 0 ;

    int i0 = ((value >> i1) & 1 ) == 1 ? 0 : -8;

    return i4 + i2 + i1 + i0;
}
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
phoenixstudio
  • 1,776
  • 1
  • 14
  • 19
  • 1
    Welcome to SO! Answers are better if you add an explanation, not just code. –  Aug 03 '19 at 23:54
  • OP just wanted to know what `!` does not so much converting his code which is fine too. Considering the OP’s attitude though I’m not sure I would have –  Aug 04 '19 at 00:14
  • Thank your for post the new code <3. and as `Chipster` some comments will be good for new ppl. but again ty <3 – CorrM Aug 04 '19 at 01:15
  • One should think about branching a bit. You have four conditions in this function. Would it be possible to replace all of them with simple boolean logic? – Ted Lyngmo Aug 05 '19 at 03:18