Why the casting to byte in BufferedOutputStream works as not expected?

3938 views java
6

I'm writing a byte to the file fileoutput.txt using following code in Java:

FileOutputStream fos=new FileOutputStream("C:/tests/fileoutput.txt");
BufferedOutputStream bos=new BufferedOutputStream(fos);

bos.write(153);
bos.flush();

To check what byte was saved in the text file I opened it in the hex editor. There I saw that the program writes the correct byte = 153 as expected.

But then I opened the sources of the write() method in the BufferedOutputStream class. This method takes the int in the argument and performs the casting from int to byte.

When the java makes this operation I expect that the program returns the different byte, not similar to the original, because in the java the byte type has the maximum at 127. And when I perform the explicit cast byte b=(int)153 the b field becomes equal to -103.

Why the write() method in the BufferedOutputStream class does the cast differently?

answered question

Casting an int to a byte just takes the 8 least significant bits out of the 32 bits constituting the integer. If you interpret these 8 bits as a signed integer number (i.e. using the first bit as a sign bit), you'll get a value between -128 and 127 (that's what Java does when it prints a byte, hence the printed value -103). If you interpret it as an unsigned integer number (that's what happens when printing the original int, since the 8th bit is not a sign bit in the case), you'll get a number between 0 and 255. -103 and 153 are just different representations of the same 8-bits binary value.

1 Answer

6

The binary representation of 153 and -103 is the same. Therefore, the correct hex value ends up in the file.

Read up on two's complement for more info: https://en.m.wikipedia.org/wiki/Two%27s_complement

posted this

Have an answer?

JD

Please login first before posting an answer.