Bitconverter for Java

Maxim Gershkovich picture Maxim Gershkovich · May 3, 2011 · Viewed 20.1k times · Source

Following the advice provided in the question https://stackoverflow.com/questions/1738244/what-is-the-java-equivalent-of-net-bitconverter I have begun implementing my own bitconverter for Java but am not getting equivalent results.

Could someone please guide me on what I might be doing incorrectly?

public static byte[] GetBytes(Integer value) {
    ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
    DataOutputStream stream = new DataOutputStream(byteStream);
    try {
        stream.writeInt(value);
    } catch (IOException e) {
        return new byte[4];
    }
    return byteStream.toByteArray();
}

byte[] result = BitConverter.GetBytes(1234); //JAVA: [0, 0, 4, -46]
byte[] result = BitConverter.GetBytes(1234); //C#: [210, 4, 0, 0]

Answer

Marc Gravell picture Marc Gravell · May 3, 2011

That is just endianness (-46 and 210 is because of Java's signed bytes, but that is just a UI thing). Either reverse the array contents, or use shift operations to write the int.

Note: the endianness that .NET emits depends on the platform. I would suggest using KNOWN ENDIANNESS in both cases; most likely by using shift operations from both. Or perhaps a better idea: just use a pre-canned, platform independent serialization format (for example: protocol buffers, which has good support on both Java and .NET/C#).

For example; if I was writing an int value to a byte[] buffer (starting at offset), I might use:

buffer[offset++] = (byte)value;
buffer[offset++] = (byte)(value>>8);
buffer[offset++] = (byte)(value>>16);
buffer[offset++] = (byte)(value>>24);

this is guaranteed little-endian, and similar code should work on any framework.