长时间找到最高有效位 [英] Find most significant set bit in a long

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

问题描述

我处在一种独特的情况下,搜索最高有效位"会产生太多结果,但找不到适合我需求的答案!

I'm in the unique situation where searching for "most significant bit" yields too many results and I can't find an answer that fits my needs!

问题本身非常简单:如何找到无符号长整数中的最高有效置位?"当我进行计算时,最右边的位是位置'0'.

The question itself is pretty simple: "How do I find the most significant set bit in an unsigned long?" When I do my calculations the rightmost bit position is position '0'.

我知道这涉及到屏蔽最低位,检查并在增加计数的同时向左移一次,然后以最低的第二位重复,等等.

I know that it involves masking the lowest bit, checking and then shifting left to once while incrementing my count, and then repeating with the 2nd lowest, etc.

我以前已经做过,但是由于任何原因我现在都做不到.

I've done this before but for whatever reason I can't do it now.

最高有效"是指最左边的设定位,对不起造成混淆!*

下面是我正在运行的解决方案和一些测试用例:

Below is my functioning solution and a few test cases:

#include <stdio.h>

int findExponent( unsigned long L ){

    int exponent = -1;

    unsigned long shift = L;

    while( 0 != shift )
        exponent++, shift >>=1;

    if ( exponent >= 0 )
        printf("The most significant bit of L is at position %d\n", exponent);
    else{
        exponent = 0;
        printf("L is zero\n");
    }
    return exponent;
}


int main(int argc, char** argv){

    long check = 8L;

    findExponent( check );//2
    findExponent( 21421L );//14
    findExponent( 0L );//(is zero)
    findExponent( 1L );//0
}

推荐答案

如何找到无符号长整数中的最高有效位?"

"How do I find the most significant bit in an unsigned long?"

您可以向右移动直到删除最后一个1.此时,该值变为0.

You can do shifts to the right until the last 1 is droped. In this moment, the value becomes 0.

#include <stdio.h>
int main(void) {
          unsigned long x = 3333;
          unsigned long y = x;
          int p = -1;
          while (0 != y)
              p++, y >>= 1;
          if (p >= 0)
              printf("The most significative bit of x is at position %d\n", p);
          else
              printf("x is zero\n");
}

这篇关于长时间找到最高有效位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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