Search code examples
javabyteprimitive-types

What does an int value returned by InputStream.read() represent?


The documentation says read() returns the byte as an int value between 0 and 255.

What does this value represent?


Solution

  • In two's complement, the number -1 is represented by all bits set to a 1.

    Here is a byte value of -1:*

    1111 1111
    

    Here is an int value of -1:*

    1111 1111 1111 1111 1111 1111 1111 1111
    

    If we take the byte value of -1 and store it in an int without extending the sign, it becomes 255:

    0000 0000 0000 0000 0000 0000 1111 1111
    

    This is just the behavior of two's complement. Storing bytes in an int leaves us leftover bits we can use to indicate other things.

    So input stream returns byte values from 0-255, and -1 to indicate end of stream. To get the byte values, cast the int to a byte:

    int byteAsInt = inputStream.read();
    if(byteAsInt > -1) {
         byte byteValue = (byte)byteAsInt;
    
         // use the byte
    }
    

    The int values 128-255 will become interpreted as negative numbers when it is casted to the byte. Alternatively, you can perform "unsigned" arithmetic on the int.

    The bytes themselves can mean anything. For example if they are from a .txt file, they are probably straight ASCII codes. Other formats can be much more complicated.


    * 4.2:

    The integral types are byte, short, int, and long, whose values are 8-bit, 16-bit, 32-bit and 64-bit signed two's-complement integers, respectively […].