Operator '&' cannot be applied to operands of type 'ulong' and 'ulong*'

2.8k Views Asked by At

Operator '&' cannot be applied to operands of type 'ulong' and 'ulong*'

What am I doing wrong? I'm trying to find which masks a integer consists of, if that makes sense.

e.g.

63 = 1+2+4+8+16+32

unsafe
{
    UInt64 n = Convert.ToUInt64(textAttributes.Text);
    UInt64* p = &n;
    for(UInt64 i = 1; i <= n; i <<= 1) 
    {
        if (i & p) 
        {
            switch(i)
            {
                default:
                    break;
            }
        }
    }
}
3

There are 3 best solutions below

4
On BEST ANSWER

You dont need unsafe code for this.

The compiler error is legitimate since you apply the operator & between a pointer and an integer

You probably want :

    UInt64 n = 63;
    for(int i = 0; i < 64; i++) 
    {
        UInt64 j = ((UInt64) 1) << i;
        if ((j & n) != 0) 
        {
          Console.WriteLine(1 << i);
        }
    }
1
On

What you're trying to do there is a bitwise AND against a memory address. You need to dereference that pointer if you want to do anything with it:

if ((i & *p) != 0)
//       ^^ dereference

Dereferencing, via an asterisk prefix, will retrieve the value at that memory address. Without it.. its the memory address itself 1

1. In C# it is a compiler error. But that is what it is.

1
On

Well you do not need unsafe context for such operation

Try this :

static void Main(string[] args)
{
    UInt64 n = Convert.ToUInt64(63);

    int size = Marshal.SizeOf(n) * 8;
    for (int i = size - 1; i >= 0; i--)
    {
        Console.Write((n >> i) & 1);
    }
}

This will print 0000000000000000000000000000000000000000000000000000000000111111 so you will know which bit are set!