我想知道我的整数的字节大小。示例:
public static void main(String[] args) throws IOException {
int a = 256;
System.out.println(nbBytes(a));
}
static byte nbBytes(int value) {
byte l = 0;
while (value != 0) {
value >>>= 8;
++l;
}
return l;
}
它工作得很好,但我想优化这个计算。 你有提议吗? :D
最佳答案
如果您指的是运行时性能,则以下算法(最初找到最高设置位)可能是最快的。我已经修改它以返回编码整数参数所需的字节数:
private static final int[] DE_BRUIJN_BIT_POSITION_LUT = {
0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30,
8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31
};
public static int nbBytes2(int n) {
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
return DE_BRUIJN_BIT_POSITION_LUT[((n * 0x07C4ACDD) >> 27) & 0x1f] / 8 + 1;
}
即使它看起来更复杂,它也没有任何循环或条件处理,这允许优化使用现代 CPU 流水线。
将 De Bruijn 算法与您的方法进行比较,对于 0x0-0xff 范围内的输入,您的方法快约 4 倍(您的方法也不会分支)。对于 0x100-0xfff 范围内的输入,我的方法快 19 倍,输入 0x10000-0xffffff 快 28 倍,输入 >0x1000000 快 35 倍。所有数字都对我的硬件有效,在其他计算机上当然可能有所不同。
关于java - 我的 int 的字节数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13125189/