按位最显著设置位 [英] bitwise most significant set bit

查看:99
本文介绍了按位最显著设置位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找到被设置为 1 最显著位。我试图从每一个可能的方式&安培; 来或运算所有位从 1 31 键,这是行不通的。

I want to find the most significant bit that is set to 1. I have tried every possible way from & to ORing all of the bits from 1 to 31 and it doesn't work.

一样,如果百万我想有 7

推荐答案

如果你坚持使用,直接按位运算符,你可以尝试这样的事:

If you insist on directly using bitwise operators, you can try something like this:

private int mostSignificantBit(int myInt){
  int mask = 1 << 31;
  for(int bitIndex = 31; bitIndex >= 0; bitIndex--){
    if((myInt & mask) != 0){
      return bitIndex;
    }
    mask >>>= 1;
  }
  return -1;
}

我们初始化面膜 1 LT;&LT; 31 ,因为那些重新presents 1后面跟31个0。我们用这个值来测试,如果指数31(第32点)是1。当我们此值与,我们得到了一个0,除非相应的位在设置。如果是这种情况下,我们返回 bitIndex处。如果没有,那么我们通过1移动掩模到右侧,然后再试一次。我们重复,直到我们用完的地方转移,在这种情况下,它意味着没有位分别设置​​(也许你想在这里扔,而不是返回-1除外)。

We initialize the mask to 1 << 31 because that represents a 1 followed by 31 0's. We use that value to test if index 31 (the 32nd spot) is a 1. When we and this value with myInt, we get a 0 unless the corresponding bit is set in myInt. If this is the case, we return that bitIndex. If not, then we shift the mask to the right by 1 and try again. We repeat until we run out of places to shift, in which case it means none of the bits were set (maybe you want to throw an exception here instead of returning -1).

请注意,这将返回值 0 1 6 64 百万二进制)。您可以调整,如果你preFER。另请注意,我用的是无符号的运营权,而不是签署右移。这是因为这里的目的是为了处理原始比特,而不是他们的签名间pretation,但它并没有在此情况下重要,因为所有负值在循环的第一次迭代变速发生前终止。

Note that this will return the value 0 for 1 and 6 for 64 (1000000 in binary). You can adjust that if you prefer. Note also that I used the unsigned right operator rather than the signed right shift. This is because the intent here is to deal with raw bits rather than their signed interpretation, but it doesn't matter in this instance since all negative values will terminate in the first iteration of the loop before shifting occurs.

这篇关于按位最显著设置位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆