1

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!

1
  • The byte 0x87 is negative, has its high bit set. Converted to an int other one get 0xFFFFFF87, a negative number. Commented Aug 5, 2013 at 15:14

2 Answers 2

1

When the ByteBuffer is converted to a byte array, why is the second byte padded with 0xFF?

When you print with %H it casts the byte into an int. It id not the byte in the ByteBuffer which has has this many bit, but the way it is being printed. I suggest using Byte.toHexString(a[j]) instead.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for condensing my confusion down to a much more concise question, and thanks for your answer. That makes complete sense. It never occurred to me that the issue was in the printf() conversion.
When I have a test fail, at least 50% of the time it's due to something wrong with the test.
0

Try this instead:

for (int j = 0; j < a.length; j++)
   System.out.printf("a[" + j + "] = 0x%H\n", ((int) a[j]) & 0xFF);

The & 0xFF operation will cut the highest three bytes, that are created after the conversion to an int.

FYI: ((int) a[j]) & 0xFF can be written as a[j] & 0xFF and will compile exactly the same. But I wrote it initially like that to clarify what is happening.

1 Comment

Thanks for the suggestion. I tried it and that does indeed make the output more clear.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.