簡體   English   中英

解碼DataOutputStream字節數組-移位產生奇數結果

[英]Decoding DataOutputStream Byte array - Bit-Shift producing odd results

我一直在研究java源代碼,以便弄清楚當結合使用DataOutputStream和DataInputStream時java如何編碼和解碼其字節數組。 (我正在用C#寫一個框架,該框架將能夠解碼Java DataOutputStream的結果)。

將long編碼為字節流的代碼是:

public final void More ...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);
}

我知道,這是使用一系列零填充右移,以便將long轉換為一系列的8個字節。

為了將它們轉換回DataInputStream內部:

public final long More ...readLong() throws IOException {
    readFully(readBuffer, 0, 8);
    return (((long)readBuffer[0] << 56) +
    ((long)(readBuffer[1] & 255) << 48) +
    ((long)(readBuffer[2] & 255) << 40) +
    ((long)(readBuffer[3] & 255) << 32) +
    ((long)(readBuffer[4] & 255) << 24) +
    ((readBuffer[5] & 255) << 16) +
    ((readBuffer[6] & 255) <<  8) +
    ((readBuffer[7] & 255) <<  0));
}

實現這兩種方法(請參見我的ideone腳本中的代碼code ),似乎會使long的長度加倍。 (您可能會在這里看到我已經從read方法中刪除了5個(長)強制類型轉換,因為這些類型導致位移位發生在錯誤的位置)

我的問題是,當我努力使自己了解這些移位操作時,這是怎么回事? 我實現它的方式是否與Java源代碼有所不同?

我傳遞的是整數,而不是整數(即字節的一半),因此將輸出結果加倍,因為它是將兩組字節加在一起!

暫無
暫無

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

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