I'm working on a Java program in which I need to convert a short into two bytes (which will then be packed into a data packet). I'm using a ByteBuffer to perform the conversion, and it seems to work, but I'm seeing some apparent byte padding which I don't quite understand.
Here's a simple example I wrote:
import java.lang.*;
import java.io.*;
import java.nio.ByteOrder;
import java.nio.ByteBuffer;
public class Test {
public static void main(String args[]) {
short i = 27015;
String s = Integer.toHexString(i);
System.out.println( "i = " + i );
System.out.println( "s = " + s );
System.out.println( "---" );
ByteBuffer b = ByteBuffer.allocate(2);
b.order(ByteOrder.BIG_ENDIAN);
b.putShort(i);
System.out.printf("0x%H\n", b.getShort(0));
System.out.println( "---" );
byte[] a = b.array();
for( int j = 0; j < a.length; j++ )
System.out.printf("a[" + j + "] = 0x%H\n", a[j]);
System.exit(0);
}
}
This program produces the following output:
i = 27015
s = 6987
---
0x6987
---
a[0] = 0x69
a[1] = 0xFFFFFF87
When the ByteBuffer is converted to a byte array, why is the second byte padded with 0xFF? It seems like the second element of the array should be 0x87 instead of 0xFFFFFF87. Am I missing something?
Thanks!
0x87is negative, has its high bit set. Converted to an int other one get 0xFFFFFF87, a negative number.