特定整数在运行时需要多少字节?

问题描述 投票:0回答:3

这可能是一个重复的问题,但我在搜索时无法找到类似的问题。

我正在寻找一种简单有效的方法来确定int在运行时需要多少个有符号字节。

例如,考虑具有以下值的int

1     - Requires 1 Byte
10    - Requires 1 Byte
128   - Requires 2 Bytes
1024  - Requires 2 Bytes
32768 - Requires 3 Bytes
...
Integer.MAX_VALUE - Requires 4 Bytes

编辑:对我来说很明显,int需要4个bytes的内存,无论其值如何。不过,如果不是这样,我正在寻找该值占用的字节数。

理想情况下,我正在寻找的答案利用位操作,并为输入0返回值1。

java memory binary int byte
3个回答
3
投票

根据您的要求提供一线解决方案:

public int bytesCount(int n) {
    return n < 0 ? 4 : (32 - Integer.numberOfLeadingZeros(n)) / 8 + 1;
}

32 - Integer.numberOfLeadingZeros(n)返回最高一位的位置。之后,您可以轻松计算所需的字节数。


0
投票

我确信有人有一个更有效的方法来做到这一点,但简单易懂的是看到2的上限能力高于它,因此你现在可以适应多少位,那么你可以除以8得出你需要多少字节。

int bytesInInt(int i) {
    int exp = 0;
    while (Math.pow(2,exp) < i) {
        exp++;
    }
    return ((exp + 1) / 8) + 1;
}

0
投票

您可以根据数字边界检查它,这些数字可以存储在1个字节(byte),2个字节(short),3个字节中。

int bytes_needed(int n){
    if(n >= -128 && n <= 127){
        return 1;
    } else if(n >= -32768 && n <= 32767){
        return 2;
    } else if(n >= -8388608 && n <= 8388607){
        return 3;
    } else {
        return 4;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.