简体   繁体   English

解码DataOutputStream字节数组-移位产生奇数结果

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

I've been looking at the java-source in order to work out how java encodes and decodes its byte arrays when using a DataOutputStream in conjunction with DataInputStream. 我一直在研究java源代码,以便弄清楚当结合使用DataOutputStream和DataInputStream时java如何编码和解码其字节数组。 (I'm writing a framework in C# which will be able to decode the results of a Java DataOutputStream). (我正在用C#写一个框架,该框架将能够解码Java DataOutputStream的结果)。

The code for the encoding of a long to a stream of bytes is: 将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);
}

I am aware that this is using a series of Zero-Fill Right Shift's in order to convert the long into a series of 8 bytes. 我知道,这是使用一系列零填充右移,以便将long转换为一系列的8个字节。

In order to convert these back inside DataInputStream: 为了将它们转换回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));
}

Implementing these two methods (Seen here in my ideone script: code ) Seems to double the long. 实现这两种方法(请参见我的ideone脚本中的代码code ),似乎会使long的长度加倍。 (You can probably see here i have removed the 5 (long) casts from the read method as these were causing the bit shift to happen in the wrong place) (您可能会在这里看到我已经从read方法中删除了5个(长)强制类型转换,因为这些类型导致位移位发生在错误的位置)

My question is, as i am struggling to get my head around these bit shift operations, what is happening here? 我的问题是,当我努力使自己了解这些移位操作时,这是怎么回事? Is the way i have implemented it in some way different to the java-source? 我实现它的方式是否与Java源代码有所不同?

我传递的是整数,而不是整数(即字节的一半),因此将输出结果加倍,因为它是将两组字节加在一起!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM