问题
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));
}
and
for (int i = 7; i >= 0; --i) {
data[p + i] = (byte)(newl & 0xff);
newl >>= 8;
}
which of the two operations is more efficient?
回答1:
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.
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.
回答2:
There is actually a quite convenient solution for converting a long
into bytes, using an instance of ByteBuffer
:
long longValue = 123858585l;
ByteBuffer buffer = ByteBuffer.allocate(8);
buffer.putLong(longValue);
// without copy, accesses directly the interal array
System.out.println(Arrays.toString(buffer.array()));
// acquire a copy of the buffer's internal byte array
byte[] longInBytes = new byte[8];
buffer.rewind();
buffer.get(longInBytes);
System.out.println(Arrays.toString(longInBytes));
However, I don't know it's performance compared to the other solutions.
回答3:
I would prefer your second solution because it is clear how it works and clean that it works. The first could easily be out by 1. It requires quite a bit of thinking to check the bit shifts. Consider that shift and add are both single cycle ops on modern computers.
Consider you are peeling off the bytes right to left. Java traditionally uses big-endian order. You want them the other msb first.
来源:https://stackoverflow.com/questions/18687772/java-converting-long-to-bytes-which-approach-is-more-efficient