Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you differentiate -1 from 0xff when reading a byte from a Java FileInputStream?

So, I had to take a test for a job interview where I was required to write a mini app that performed simple XOR encryption, and came across this question. I used a FileInputReader to pull each byte in, perform an XOR operation with the key, and pushed the result back out a FileOutputStream. Heres what got me thinking.

FileInputStream returns an int, a 32-bit signed type. When receiving only one byte, you can cast it into a 'byte' type. FileInputStream also returns -1 if it reaches EOF. But, -1 == 0xff in two's complement binary, so what if the byte read is really 0xff, not EOF?

Is 0xff a byte that mathematically won't ever be returned except in special cases (such as EOF)? Or is this a situation that you may have to account for depending on the data you are reading?

like image 651
Ron Brown Avatar asked Jul 23 '26 02:07

Ron Brown


2 Answers

No, -1 in an int is not 0xff, but 0xffffffff. An int is 32 bits in Java.

Before casting the value to byte, check if it is -1.

The API documentation of the read method of class FileInputStream explains this:

Reads the next byte of data from this input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.

So, if a byte with the value 0xff is found in the input, the read method will return an int with the value 255 (0xff). Only on EOF will it return -1 (which is 0xffffffff when stored in an int).

like image 81
Jesper Avatar answered Jul 25 '26 15:07

Jesper


You could:

int value = is.read();
if (value == -1)
   // the end!
else
{
   byte b = (byte) value;
   // use b
}

Anyway I should use chunk reads (try to read to a byte array) and if the returned byte count is zero, then we are finished:

int count;
byte[] buffer = new byte[8192];
while ((count = is.read(buffer)) > 0) {
   // use buffer from pos 0 to pos count-1
}
like image 23
helios Avatar answered Jul 25 '26 16:07

helios



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!