Java将长整数转换为字节-哪种方法更有效 [英] Java Converting long to bytes - which approach is more efficient
本文介绍了Java将长整数转换为字节-哪种方法更有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两种方法可以将long转换为字节数组.
I have two approaches to convert long to byte array.
for (int i = 0; i < 7; i++) {
data[pos + i] = (byte) (value >> (7- i - 1 << 3));
}
和
for (int i = 7; i >= 0; --i) {
data[p + i] = (byte)(newl & 0xff);
newl >>= 8;
}
这两个操作中哪个更有效?
which of the two operations is more efficient?
推荐答案
我建议您看看Java代码是如何做到的.
I suggest you look at how the Java code does it.
public final void writeLong(long v) throws IOException {
writeBuffer[0] = (byte)(v >>> 56);
writeBuffer[1] = (byte)(v >>> 48);
writeBuffer[2] = (byte)(v >>> 40);
writeBuffer[3] = (byte)(v >>> 32);
writeBuffer[4] = (byte)(v >>> 24);
writeBuffer[5] = (byte)(v >>> 16);
writeBuffer[6] = (byte)(v >>> 8);
writeBuffer[7] = (byte)(v >>> 0);
out.write(writeBuffer, 0, 8);
incCount(8);
}
如您所见,没有循环,您的操作就会减少.
as you can see, without a loop you have less operation.
最快的方法是完全不执行此操作,而是使用Unsafe.writeLong(),因为这会花费很长时间并将其直接放入内存中,而不是将其分解为字节.这样可以快十倍以上.
The fastest way is to not do this at all and instead using Unsafe.writeLong() as this take a long and places it directly into memory instead of breaking it into bytes. This can be more than 10x faster.
这篇关于Java将长整数转换为字节-哪种方法更有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文