取消除最重要位C#以外的所有位

时间:2017-06-15 17:38:18

标签: c# bit-shift bits unset

是否有一种快速简便的方法可以取消除最高位之外的数字中的所有位?换句话说,我想取一个整数x并应用&操作数为1的运算符,左移位为x中的总位数。 示例:

return UnsetAllBitsExceptMSB(400);

应返回256

4 个答案:

答案 0 :(得分:2)

是的,有一招:

private int UnsetAllBitsExceptMSB(int x)
{
  x |= x >> 16;
  x |= x >> 8;
  x |= x >> 4;
  x |= x >> 2;
  x |= x >> 1;
  x ^= x >> 1;
  return x;
}

首先打开最高有效位设置位右侧的所有位(00110000变为001111111)。然后使用XOR,结果右移一个,然后关闭第一个位。 (00111111 XOR with 00011111 = 00100000)

还有其他方法可以在某些情况下表现更好,但无论输入如何,这都有可预测的性能。 (5或6,右移和异或)。

答案 1 :(得分:1)

我不确定"快捷方便"但是你不需要任何按位操作...你的问题可以改写为"怎么可以我发现2的最大功率小于我的输入?所以这是一个简单的方法:

#replcace data with below line
data = json.loads(links)

#replace your last loop with below
if data and 'url' in data[0]:
 for i in data[0]['url']:
  url = 'http://example.com/placeforfiles{}'.format(i)
  print(url)

答案 2 :(得分:0)

鉴于int表示32位有符号整数,我猜第一位不应该被考虑在内。所以,这应该得到你想要的:

int result = 1 << 30;
while ((result & myInt) != result)
    result >>= 1;

答案 3 :(得分:0)

您好,这是另一个需要考虑的选择:

public static int GetTopBitValue(int number)
{
    if (number < 0)
    {
        throw new ArgumentOutOfRangeException("Non negative numbers are expected");
    }

    int i = 1;
    while (i <= number)
        i = i << 1;

    return i >> 1;
}

编辑以涵盖角落案件。

相关问题