【问题标题】:Operator '&' cannot be applied to operands of type 'ulong' and 'ulong*'运算符“&”不能应用于“ulong”和“ulong*”类型的操作数
【发布时间】:2014-05-29 03:33:24
【问题描述】:

运算符“&”不能应用于“ulong”和'ulong*'类型的操作数

我做错了什么?如果有意义的话,我正在尝试找出整数包含哪些掩码。

例如

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;
            }
        }
    }
}

【问题讨论】:

  • 你的意思是i &amp; n != 0?我看不出需要多么不安全的代码。
  • @JeroenVannevel 注意错误中的星号。
  • 相关帖子here.

标签: c# unsafe ulong


【解决方案1】:

你不需要不安全的代码。

编译器错误是合法的,因为您在指针和整数之间应用了运算符 &

你可能想要:

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

【讨论】:

  • 运算符“
  • 只给我 0, 1, 2, 3, 4, 5 但我想那更好。谢谢!
  • 为您的预期输出编辑(我将 WriteLine(i) 替换为 WriteLine(1
  • 非常感谢!我已经被这个问题困了好几个小时了>.
【解决方案2】:

你试图做的是对内存地址进行按位与。如果你想对它做任何事情,你需要取消引用该指针:

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

通过星号前缀取消引用将检索该内存地址处的值。没有它..它的内存地址本身 1

1.在 C# 中,这是一个编译器错误。但事实就是如此。

【讨论】:

  • 成功了,谢谢。有什么方法可以在不使用 unsafe 的情况下做到这一点?
【解决方案3】:

这样的操作不需要不安全的上下文

试试这个:

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);
    }
}

这将打印0000000000000000000000000000000000000000000000000000000000111111,这样您就可以知道设置了哪些位!

【讨论】:

  • 我有点想避免这种情况。不过还是谢谢。
猜你喜欢
  • 2014-05-27
  • 2023-04-07
  • 1970-01-01
  • 1970-01-01
  • 2019-08-27
  • 2021-07-27
  • 2020-10-19
  • 2015-01-25
  • 2011-12-31
相关资源
最近更新 更多