質問

I am trying to take the 11 msb bits and get their value like this:

value = lineIntData & 0xFFE00000 >> 21;

lineIntData is a number of 8 hexadecimal digits.

What I don't understand is why I get a compilation error saying "Cannot Implicitly convert Long to Int". The error disappears if I either take one digit out of the hex mask (thus making it 7 digits) or if I change int from int to long.

Why do I even get this error? Isn't a single hex digit takes 4 bits, which means 8 digits is 32 bits so it should all fit a single Int32? If I'm doing it wrong, then how can I take the value of the 11 msbs of the number?

役に立ちましたか?

解決

The problem is that the type of 0xFFE00000 is uint (because it's greater than 0x7fffffff), and there's no &(int, uint) operator, so both sides are promoted to long.

The fix is simple: just shift and then mask:

value = (lineIntData >> 21) & 0x7ff;

Now everything stays an int throughout.

By the way, I personally always use brackets when shifting and masking. It means I don't need to remember the precedence rules for those operators. While I remember precedence for some operators, this is one case where I'd rather just use brackets.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top