• Post Reply Bookmark Topic Watch Topic
  • New Topic

reading a multibyte value from a file  RSS feed

 
Joy DeGrazzio
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think this should be obvious but I'm missing something.
I'm using RandomAccessFile to read a sequence of bytes into a byte array. I just don't know how to convert this byte array into an actual number other than looping thru the array. But I don't think that will give me the right value.
example:

Is there some way to just read the next 2 bytes as an int instead of reading it into a byte array?
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch! Please choose just one forum for each question you post -- no cross-posting!
RandomAccessFile implements the DataInput interface, which means it has a readInt() method that does exactly that. Of course, ints have 4 bytes, not 2, so perhaps you want readShort() instead. Also note that these methods expect the data to be "big-endian" (network byte order, or most significant byte first depending on where the data file comes from, this may or may not be the case.
Look at the Javadocs for RandomAccessFile -- it has lots of useful methods.
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Joy,
Welcome to JavaRanch. Assuming you know the exact layout of the file then you can just use the readXXX() methods of RandomAccessFile. In your example above, assuming that the value is a 16 bit integer then you could do something like:

That will read the next two bytes at the current file pointer and convert it to a short (16 bit int) using the following:

where b1 is the first byte read and b2 the second.
RandomAccessFile has methods to read all of the Java primitives so I would encourage you to look at the API docs to learn more.
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Something wierd is going on here with UBB. EFH's post was not here when I started my post even though the time shows to be 4 hrs before mine, and I got a couple of zero sized thread errors while posting.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!