I need to convert numerical values into byte arrays. For example, to convert a long to a byte array, I have this method:
public static byte[] longToBytes(long l) {
ByteBuffer buff = ByteBuffer.allocate(8);
buff.order(ByteOrder.BIG_ENDIAN);
buff.putLong(l);
return buff.array();
}
It's pretty straightforward - take a long, allocate an array that can hold it, and throw it in there. Regardless of what the value of l
is, I will get an 8 byte array back that I can then process and use as intended. In my case, I'm creating a custom binary format and then transmitting it over a network.
When I invoke this method with a value of 773450364, I get an array [0 0 0 0 46 25 -22 124]
back. I have code that also converts byte arrays back into their numerical values:
public static Long bytesToLong(byte[] aBytes, int start) {
byte[] b = new byte[8];
b[0] = aBytes[start + 0];
b[1] = aBytes[start + 1];
b[2] = aBytes[start + 2];
b[3] = aBytes[start + 3];
b[4] = aBytes[start + 4];
b[5] = aBytes[start + 5];
b[6] = aBytes[start + 6];
b[7] = aBytes[start + 7];
ByteBuffer buf = ByteBuffer.wrap(b);
return buf.getLong();
}
When I pass the array from the other method back into this method, I get 773450364, which is correct.
Now, I transmit this array over TCP to another Java client. The documentation for the java.io.InputStream.read()
method says that it returns a int
value between 0 and 255, unless the end of the stream is reached and a -1 is returned. However, when I use it to populate a byte array, I continue to get the negative values on the receiving side. I suspect this has to do with overflow (a value of 255 can not fit into a Java byte, so when I put it into the byte array, it overflows and becomes negative).
This brings me to my problem. The existance of the negative numbers concerns me. Right now, I'm developing the Java side of an application, where a byte is between -128 and 127 inclusive. The other endpoint might be in C, C++, Python, Java, C#...who knows. I'm not sure how the existance of a negative value in some byte arrays are going to affect processing. Other than documenting this behavior, what can/should I do to make it easier for myself and future developers working on this system, especially in endpoints that are not written in Java?