[c#] long and bitwise & operator

S

seb666fr2

hello,

Anybody can tell me why it is impossible to use the '&' operator
with operands of type 'long' or 'ulong' and what i must use instead
of this?


thanks.
 
G

Guest

Not really sure what you mean, works fine for me using the following test:

public class OrApp
{
public static void Main()
{
long a = 0xF0F0F001;
long b = 0x0B0BF010;
ulong c = 0xF0F0F001;
ulong d = 0x0B0BF010;
System.Console.WriteLine(string.Format("{0:X}",a & b));
System.Console.WriteLine(string.Format("{0:X}",c & d));
}
}

Can you give more info about the kind of error/problem you encounter?

rgds,
Baileys
 
S

seb666fr2

thanks for the response.

with it, i have been able to find the problem. it was a mistake
from me (i think) because i used long instead of ulong. however,
the error reported by the compiler is relatively strange
(cs0019:Operator '&' cannot be applied to operands of type 'long' and
'ulong').

here is a sample code :

public class StrangeLongCompileError {
public static void Main(string[] pArgs) {
long lValue = 0x7f00000000000000L;
byte lbyte0 = (byte)((lValue & 0xff00000000000000L) >> 56);
}
}

the code above does not compile because the lValue is a long and the
mask is greater than 0x7f00000000000000L.
 
G

Guest

Ah, now i get it (I should have tested my example with more extreme long
values before posting).

Anyway, i think you misinterpret what the compiler is telling you: for
long/ulong (=Int64/UInt64) there are 2 predefined & (binary)-operators:
long operator &(long x, long y);
ulong operator &(ulong x, ulong y);

what you're trying to accomplish is the following:
operator &(long x, ulong y);

your first operand is a long, your second operand is of type ulong (you can
verify this: Console.WriteLine(0xff00000000000000L.GetType());)

There is no implicit conversion between ulong and long, so the compiler is
telling you that there is no binary &-operator defined that can do what you
ask it to do.

Bottom line: & will work if both operands are long, or both operands are
ulong, but not mixed.

HTH,
Baileys
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top