Search code examples
javaarraysbytearrayoutputstream

Adding two data types in bytearrayoutputstream and printing it


I have used the following code. I just can't seem to get the value of x back from the byte array. Here is my code:

int seqNo = 0;
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    DataOutputStream out = new DataOutputStream(bout);
    try {
        out.writeInt(seqNo);
        String i = Integer.toString(seqNo) + "hello";
        byte[] b = i.getBytes();
        System.out.println(Arrays.toString(b));
        int x = b[0];
        System.out.println(x);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Here is the output:

[48, 104, 101, 108, 108, 111]
48

The output should contain 0 instead of 48. Please help


Solution

  • 48 is the ASCII code of 0

     int x=b[0]-48;