• Post Reply Bookmark Topic Watch Topic
  • New Topic

read() VS read(byte[]) in RandomAccessFile  RSS feed

 
Kelly Wood
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
These two methods do not seem to behave the same way. In one case, read() returns 182, while read(byte[]) returns -74 (by passing in new byte[1]). Does anyone know what is going on?
 
Edwin Dalorzo
Ranch Hand
Posts: 961
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What exactly do you mean.

Well, I tested this code, and both produce the same result:



This produces the same result:

 
Joe Ess
Bartender
Posts: 9406
12
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java numeric types are signed using a system called Two's Complement, where the left-most bit signals the sign of the number. If you read a byte value of B6 into an 32-bit integer, the left-most bit is 0, so it is interpreted as a positive 182. If you read the same value into an 8-bit byte, the left-most bit is 1 and it is interpreted as -74. What you need to do is select the correct method to read the data that you have. If you are reading byte data, use read(byte[]). If you are reading character data, use readChar/readUTF and so on.
[ June 14, 2006: Message edited by: Joe Ess ]
 
Kelly Wood
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I see, thanks guys.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!