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
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.
write() method in the
BufferedOutputStream class does the cast differently?
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