解码DataOutputStream字节数组 - Bit-Shift产生奇数结果

时间:2014-04-16 13:20:11

标签: java byte bit-shift

我一直在研究java-source,以便在将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);
}

我知道这是使用一系列零填充右移,以便将长转换为一系列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)似乎要加倍长。 (您可以在这里看到我已经从read方法中移除了5个(长)强制转换,因为这些导致位移发生在错误的位置)

我的问题是,因为我正在努力解决这些位移操作,这里发生了什么?我以不同于java-source的方式实现它的方式是什么?

1 个答案:

答案 0 :(得分:1)

我传递的是整数而不是长整数,这是字节的一半,因此它将输出加倍,因为它一起添加了两组字节!

相关问题