int中使用的计数位数 [英] Count bits used in int

查看:138
本文介绍了int中使用的计数位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您有二进制数10110,我怎么能让它返回5?例如,一个数字,告诉我们使用了多少位?下面列出了一些类似的例子:

If you have the binary number 10110 how can I get it to return 5? e.g a number that tells how many bits are used? There are some likewise examples listed below:


  • 101应该返回3

  • 000000011应该返回2

  • 11100应该返回5

  • 101010101应该返回9

  • 101 should return 3
  • 000000011 should return 2
  • 11100 should return 5
  • 101010101 should return 9

如何在Java中获得最简单的方法?我提出了以下方法,但我可以更快地完成:

How can this be obtained the easiest way in Java? I have come up with the following method but can i be done faster:

public static int getBitLength(int value)
{
    if (value == 0)
    {
        return 0;
    }
    int l = 1;
    if (value >>> 16 > 0) { value >>= 16; l += 16; }
    if (value >>> 8 > 0) { value >>= 8; l += 8; }
    if (value >>> 4 > 0) { value >>= 4; l += 4; }
    if (value >>> 2 > 0) { value >>= 2; l += 2; }
    if (value >>> 1 > 0) { value >>= 1; l += 1; }
    return l;
}


推荐答案

最简单?

32 - Integer.numberOfLeadingZeros(value)

如果您正在寻找算法,Java API的实现者会同意您的分而治之的位移方法:

If you are looking for algorithms, the implementors of the Java API agree with your divide-and-conquer bitshifting approach:

public static int numberOfLeadingZeros(int i) {
    if (i == 0)
        return 32;
    int n = 1;
    if (i >>> 16 == 0) { n += 16; i <<= 16; }
    if (i >>> 24 == 0) { n +=  8; i <<=  8; }
    if (i >>> 28 == 0) { n +=  4; i <<=  4; }
    if (i >>> 30 == 0) { n +=  2; i <<=  2; }
    n -= i >>> 31;
    return n;
}

编辑:提醒信任的人在浮点计算的准确性中,运行以下测试工具:

Edit: As a reminder to those who trust in the accuracy of floating point calculations, run the following test harness:

public static void main(String[] args) {
    for (int i = 0; i < 64; i++) {
        long x = 1L << i;
        check(x);
        check(x-1);
    }
}

static void check(long x) {
    int correct = 64 - Long.numberOfLeadingZeros(x);
    int floated = (int) (1 + Math.floor(Math.log(x) / Math.log(2)));
    if (floated != correct) {
        System.out.println(Long.toString(x, 16) + " " + correct + " " + floated);
    }
}

第一个检测到的偏差是:

The first detected deviation is:

ffffffffffff 48 49

这篇关于int中使用的计数位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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