Bitwise operation on long

I am 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 to do it?

+3


source to share


6 answers


See http://msdn.microsoft.com/en-en/library/aa664674%28v=vs.71%29.aspx .

If the literal suffix has not, it is first of these types, which can be represented by its value: int

, uint

, long

, ulong

.

You have

0xFFFFFFFFFFFFFC00

      



but Int64.Max:

0x7FFFFFFFFFFFFFFF

      

therefore it is long

not large enough, but ulong

taken as a literal type.

Now you have the left side of a Int64

which is signed, and on the right side you have ulong

, however, no overload &=

that accepts this combination, resulting in an error.

+4


source


C # uses the smallest fit type for integer literals and 0xFFFFFFFFFFFFFC00 is too long so it is coolest.



So either convert itag to ulong or 0xFFFFFFFFFFFFFC00 to long (unchecked).

+2


source


Signed and unsigned "numbers" cannot be matched against mixes, and Int64 is signed so that it doesn't work.

I would say:

UInt64 itag = BitConverter.ToUInt64(temp, 0); //note the added 'U' to make it unsigned
itag &= 0xFFFFFFFFFFFFFC00; //Now types match, they're both unsigned.

      

+1


source


itag

is long. 0xFFFFFFFFFFFFFC00

- ulong. You are trying to mix both in a statement &=

that doesn't work.

Why is your literal ulug? MSDN says :

If the literal has no suffix, it is the first of these types in which its value can be represented: int, uint, long, ulong.

Since the number is too large for an int, uint, or long, your literal becomes ulong.

You have two options, either declare itag

as ulong as others have suggested, or (bitwise) convert your literal to long:

itag &= unchecked((long)0xFFFFFFFFFFFFFC00);

      

This will overflow your ulong to a (negative) long.

+1


source


Section 7.11.1 Boolean Integer Operators of the C # Language Specification read:

Predefined integer logical operators:

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 long

is no predefined operator between (which is just an alias for Int64

) and ulong

, hence the error.

+1


source


The problem is when you are trying to execute &=

a long

and ulong

.

Just replacing Int64

with ulong

solves the problem, because then you are applying &=

to 2 ulong

s.

0


source







All Articles