【问题标题】:Remove value from bitwise or-combined integer?从按位或组合整数中删除值?
【发布时间】:2015-07-11 15:51:53
【问题描述】:

使用按位或运算符,您可以将整数(例如 2 的幂的整数)相互组合,然后检查返回的 int 是否包含指定值。但是有没有合适的方法从返回的整数中删除值而不合并一个新的值?

目前我从组合整数中减去要删除的值,但这是否可以正常工作还是会导致问题?还是有更“正确”的做法?

这是我的代码:

private void button1_Click(object sender, EventArgs e)
{
    int combinedints = CombineIntegers(CombineIntegers(2, 8), 32); //Combine three integers.
    MessageBox.Show(combinedints.ToString()); //Shows 42.
    MessageBox.Show(RemoveInteger(combinedints, 8).ToString()); //Removes 8 - shows 34.
}

private int CombineIntegers(int a, int b)
{
    return a | b;
}

private int RemoveInteger(int a, int b)
{
    return a -= b;
}

private bool CheckInteger(int a, int b)
{
    return (a & b) == b;
}

【问题讨论】:

  • "组合整数,即 2 的幂,彼此' - 你也可以组合其他整数。
  • @GolezTrol:已更改... :)
  • RemoveInteger 是什么概念?如果unset,那就大错特错了。
  • @leppie :这个想法是从主整数中删除一个值。如果我将 2、8 和 32 结合起来,它将等于 42。然后我可以使用 RemoveInteger 删除其中一个值,如果我愿意的话。 (如 8 个)。
  • @VisualVincent:但是考虑到combine 的含义是像您接受的答案所暗示的按位运算吗? ;p

标签: c# bitwise-operators bitwise-or


【解决方案1】:
private int RemoveInteger(int a, int b)
{
    return a & ~b;
}

【讨论】:

  • 这是合乎逻辑的,但 OP 并不暗示它。
  • @leppie :检查值也是合乎逻辑的。重要吗,还是……?
  • @VisualVincent:这称为位运算或更正确的布尔数学(基于布尔代数)。阅读它,你可以用一系列的 1 和 0 来做非常有趣的事情:D
猜你喜欢
  • 2017-06-23
  • 1970-01-01
  • 1970-01-01
  • 2019-10-03
  • 2012-02-11
  • 1970-01-01
  • 1970-01-01
  • 2015-08-29
  • 1970-01-01
相关资源
最近更新 更多