• Post Reply Bookmark Topic Watch Topic
  • New Topic

FilteInputStream and byte  RSS feed

 
Stefan Geelen
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I was confused looking in the JavaDoc API and finding following method:
read(byte[] b) : Reads up to b.length bytes of data from this input stream into an array of bytes.
Now a byte in Java is signed (max value 0x80), so how can the FileInputStream read correctly a binary file where there are bytes having a value bigger than 0x80 ?
If I try to compile : byte[] b = {0x98, 0xcb, 0xfe, 0x00}; I get the 'possible loss of precision: int, required: byte' error.
So isn't there also loss of precision using the read(byte[] b) method ?
Regards,
Stefan
 
Dave Landers
Ranch Hand
Posts: 401
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The bits are read as-is from the stream. So if the file contains FF (binary 1111 1111), for example, those bits will be shoved into the byte[]. In java, that will show up as a byte value of -1.
So there is no loss of precision - the exact stuff from the stream is in the byte[]. When it's "in the stream", it really has no meaning - it is just 1's and 0's. But once it is in the byte, it now has some "meaning", and that meaning includes the MSB being a sign (+/-) bit, etc.
If you want to know what was in the file in the "traditional way" (i.e. what hex character), you can use something based on Integer.toHexString(). I've got this in some code I use:

The reason you get a loss of precision warning when you do
byte[] foo = { 0x98 };
or whatever is becausew 0x98 is an int = 152 and it won't fit in a byte. If you change that to
byte[] foo = { (byte)0x98 };
then the compiler will "know what you mean" and give you the byte vaule you are probably expecting (which is = -104).
[ October 22, 2002: Message edited by: Dave Landers ]
 
Stefan Geelen
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Dave,
thx for your clear explanation.
Regards,
Stefan
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!