Numerical Limits of writeByte() in Java

后端 未结 1 710
深忆病人
深忆病人 2021-01-29 14:42

The data output stream method writeByte(int), as the name suggests, writes a one byte int over the stream.

What are the limits of this? Is it 256 or is it signed and it

1条回答
  •  无人及你
    2021-01-29 15:09

    writeByte(int) invokes write(int). The documentation of write(int) says:

    Writes the specified byte (the low eight bits of the argument b) to the underlying output stream.

    Therefore it doesn't matter what range of integers the int argument lies in. Two arguments that differ by a multiple of 256 will cause that same byte to be written.

    One easy way to test this is to use a ByteArrayOutputStream. Try this program:

    public static void main(String[] args) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(baos);
        dos.writeByte(-128);
        dos.writeByte(-128 + 256);
        System.out.println(Arrays.toString(baos.toByteArray()));
    }
    

    The output is [-128, -128] because the same byte has been written twice.

    0 讨论(0)
提交回复
热议问题