这很可能是一个重复的问题,但我在搜索时找不到类似的问题。
我正在寻找一种简单、高效的方法来确定 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 个 byte
内存,无论其值如何。尽管如此,我正在寻找如果不是这种情况该值将占用的字节数。
理想情况下,我正在寻找的答案是利用位操作并为输入 0 返回值 1。
最佳答案
根据您的要求提供一条线解决方案:
public int bytesCount(int n) {
return n < 0 ? 4 : (32 - Integer.numberOfLeadingZeros(n)) / 8 + 1;
}
其中 32 - Integer.numberOfLeadingZeros(n)
返回最高一位的位置。之后,您可以轻松计算出所需的字节数。
关于java - 特定整数在运行时需要多少字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47913909/