我需要 Java 中的一个函数来提供表示给定整数所需的字节数。当我传递 2 时,它应该返回 1、400 -> 2、822222 -> 3 等。
@Edit:现在我坚持这个:
numOfBytes = Integer.highestOneBit(integer) / 8
不知道 HighestOneBit() 到底做什么,但也尝试过:
numOfBytes = (int) (Math.floor(Math.log(integer)) + 1);
我在某个网站上找到的。
最佳答案
static int byteSize(long x) {
if (x < 0) throw new IllegalArgumentException();
int s = 1;
while (s < 8 && x >= (1L << (s * 8))) s++;
return s;
}
关于java - 如何确定表示给定整数所需的字节数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8377050/