问题
I trying to compile this code:
Int64 itag = BitConverter.ToInt64(temp, 0);
itag &= 0xFFFFFFFFFFFFFC00;
However this gives me the following error:
Operator '&=' cannot be applied to operands of type 'long' and 'ulong'
How do I do this?
回答1:
See http://msdn.microsoft.com/en-en/library/aa664674%28v=vs.71%29.aspx .
If the literal has no suffix, it has the first of these types in which its value can be represented:
int
,uint
,long
,ulong
.
You have
0xFFFFFFFFFFFFFC00
but Int64.Max is:
0x7FFFFFFFFFFFFFFF
so long
is not big enough and ulong
is taken as the type of the literal.
Now you have on the left side a Int64
, which is signed, and on the right side you have ulong
, however, there is not overload of &=
which accepts that combination, which leads to the error.
回答2:
C# uses the smallest fitting type for integer literals and 0xFFFFFFFFFFFFFC00 is too big for long so it's an ulong.
So either convert itag to ulong or 0xFFFFFFFFFFFFFC00 to long (unchecked).
回答3:
Signed and unsigned "numbers" cannot be mix-matched, and Int64 is signed so it's a no-go.
I'd go like this:
UInt64 itag = BitConverter.ToUInt64(temp, 0); //note the added 'U' to make it unsigned
itag &= 0xFFFFFFFFFFFFFC00; //Now types match, they're both unsigned.
回答4:
itag
is a long. 0xFFFFFFFFFFFFFC00
is a ulong. You are trying to mix both in a &=
statement, which doesn't work.
Why is your literal a ulong? MSDN says:
If the literal has no suffix, it has the first of these types in which its value can be represented: int, uint, long, ulong.
Since the number is too large for int, uint or long, your literal becomes a ulong.
You have two options: Either declare itag
as a ulong, as others have suggested, or (bitwise) convert your literal into a long:
itag &= unchecked((long)0xFFFFFFFFFFFFFC00);
This will overflow your ulong into a (negative) long.
回答5:
Section 7.11.1 Integer logical operators of the C# Language Specification reads:
The predefined integer logical operators are:
int operator &(int x, int y);
uint operator &(uint x, uint y);
long operator &(long x, long y);
ulong operator &(ulong x, ulong y);
As you can see, there's no predefined operator between long
(which is just an alias for Int64
) and ulong
, hence the error.
回答6:
The problem is that you're trying to &=
a long
and an ulong
.
Just replacing the Int64
with a ulong
solves the problem because then you are applying &=
to 2 ulong
s.
来源:https://stackoverflow.com/questions/9924762/bitwise-operation-on-longs