【问题标题】:How can I calculate required bits for an unsigned value? [duplicate]如何计算无符号值所需的位? [复制]
【发布时间】:2022-01-02 05:34:23
【问题描述】:

对于给定的无符号int 值,我尝试了以下方法来存储给定值的位数。

    // Returns the number of required bits for (storing) specified unsigned value.
    static int size(final int value) {
        if (value < 0) {
            throw new IllegalArgumentException("value(" + value + ") is negative");
        }
        return (int) Math.ceil(Math.log10(value) / Math.log10(2));
    }

我得到了什么。

size for 1310394095: 31              (RANDOM)
size for 1: 0                        (1; Not Good; should be 1)
size_NotNegative_Zero() is @Disabled (0; ERROR; Expecting actual: -2147483648 ...)
size for 2147483647: 31              (Integer.MAX_VALUE)

Integer.MAX_VALUE31 似乎没问题。

我该如何解决这个问题?

【问题讨论】:

标签: java logarithm


【解决方案1】:

虽然我将自己的问题标记为重复,但我还是发布了我发现的问题。

问题在于输入不仅是正数,还包括零,这就是为什么简单地将 logwhatevervlog 相除的原因whatever2 不起作用,因为 logwhatever0 没有定义。

这就是我用https://stackoverflow.com/a/680040/330457 得出的结论。

    static int size(final int value) {
        if (value < 0) {
            throw new IllegalArgumentException("value(" + value + ") is negative");
        }
        if (value == 0) {
            return 1;
        }
        return Integer.SIZE - Integer.numberOfLeadingZeros(value);
    }
size for 909663241: 30  (RANDOM)
size for 1: 1           (ONE)
size for 0: 1           (ZERO)
size for 2147483647: 31 (Integer.MAX_VALUE)

【讨论】:

    猜你喜欢
    • 2019-11-19
    • 2016-08-17
    • 2018-11-05
    • 2011-11-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-23
    • 2020-04-25
    • 1970-01-01
    相关资源
    最近更新 更多