簡體   English   中英

Java將long轉換為字節 - 哪種方法更有效

[英]Java Converting long to bytes - which approach is more efficient

我有兩種方法來轉換長到字節數組。

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;
}

哪兩個操作更有效?

我建議你看一下Java代碼是如何做到的。

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);
}

正如您所看到的,沒有循環您可以減少操作。

最快的方法是不要這樣做,而是使用Unsafe.writeLong(),因為這需要很長時間並將其直接放入內存而不是將其分成字節。 這可以快10倍以上。

實際上有一個非常方便的解決方案,使用ByteBuffer實例將long轉換為字節:

    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));

但是,與其他解決方案相比,我不知道它的性能。

我更希望你的第二個解決方案,因為它很清楚它是如何工作的,並且它是干凈的。 第一個可以很容易地用1表示。需要相當多的思考來檢查位移。 考慮到移位和添加都是現代計算機上的單周期操作。

考慮一下從右到左剝離字節。 Java傳統上使用big-endian命令。 你首先想要的是另一個msb。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM