Search code examples
javaarraysbytearrayoutputstream

Printing byte array filled from bytearrayoutputstream


I have filled a byte array using ByteArrayOutputStream. When I print it, the output is confusing. I need some guidance.

Here is my code:

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    DataOutputStream out = new DataOutputStream(bout);
    try {
        out.writeInt(150);
        byte[] b = bout.toByteArray();
        System.out.println(Arrays.toString(b));

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Here is my output:

[0, 0, 0, -106]

Please help


Solution

  • 150 equals to 1001 0110 which is in term of byte's bits -128 (the left most bit) plus 2 + 4 + 16 = -106