Question

Hy guys! I've been searching for some old posts about Serialization in Java. I want to convert an Object into a ByteArray. So far I´ve done this:

public class test 
{

    public static void main(String[] args) throws IOException 
    {
        // 00111111 00111111 00111111 11110000  - in bytes: 63, 63, 63, 240
        int x = 1061109744; 
        byte[] bytes = null;

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutput out = null;
        try {
            out = new ObjectOutputStream(bos);   
            out.writeObject(x);
            bytes = bos.toByteArray();

        } 
        finally 
        {
            out.close();
            bos.close();
        }

        System.out.println("Lenght: " + bytes.length);

        for(int i=0; i < bytes.length; i++)
        {
            System.out.println(bytes[i]);
        }
    }
}

Apparently it works good but it introduces a lot of "junk" into the ByteArray. The values that really have interest to me are the last 4 bytes that correspond to my "int x = 1061109744;".

Why does this happen?

Is it possible to avoid the "junk" values?

Is it possible to surpass the "signed" values? (I have to write byte values bigger than 128).

Was it helpful?

Solution

Is it possible to avoid the "junk" values?

Yes. Write out an int, not an Object. By passing an int to writeObject, you're promoting it (autoboxing it) to Integer, which means that the serialized information contains header information saying that it's an Integer object, not an int. Your ByteArrayOutputStream has a write(int) method that writes a byte (the low-order 8 bits of the int) to the output stream. Whether those are signed or not is purely a matter of interpretation, not the bits in the stream.

OTHER TIPS

Use DataOutputStream and field by field serialization:

ByteOutputStream baos = new ByteOuputStream();
DataOutputStream dos = new DataOutputStream(baos);

dos.writeInt(x);

dos.close();
bytes = baos.toByteArray();

In the byte array all elements are signed (naturally). But if you want to print them unsigned:

for(int i=0; i < bytes.length; i++)
{
    System.out.println(0xFF & bytes[i]);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top