• Post Reply Bookmark Topic Watch Topic
  • New Topic

DataInputStream.readInt() vs. reading 4 bytes  RSS feed

 
Barry Andrews
Ranch Hand
Posts: 529
C++ Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I am trying to read 4 bytes from a file using the DataInputStream, but I am not getting the correct integer back. If I use the readInt() method, I get -8355712 which is what I am expecting, but if I use readByte() 4 times and do some bit shifting and addition, I get -25198720, which is wrong. You may wonder why I just don't use readInt(), but believe me the other way is what I need in my special case.

Does anyone have some insight as to why this does not work?

many thanks,
Barry
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes - readByte() returns a byte, in the range -128 to +127. If this is negative, then when you convert it to int, it acquires 1's in the first 12 bits. These screw you up when you combine the parts as you do. Try someting like
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's also worthwhile to look at the documentation for readInt() (following links as necessary) to see what it says there.
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You will have corrected Jim's typo, but in case you didn't its code should read with only one ampersand:

Cheers
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes - thanks.
 
Barry Andrews
Ranch Hand
Posts: 529
C++ Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ah yes!!!........ Thanks, folks! I appreicate the help!

Barry
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!