• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

extracting bytes from byte array

 
Gary Frick
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would never have guessed that working at the byte level in Java would be so tough. I'm having to work with a structured blob that is retrieved from a database. The structured blob is a series of tokenized data in the following form:
2-byte (int) Token ID
2-byte (int) Date Type
2-byte (int) Data Length
n-byte (?) Data value
If I load this structured blob into a byte array, how do I extract these binary and other values from the array and put them into particular variables?
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'd say the easiest way to do this in Java is something like

Note that when using DataInputStream, detecting the end of file can be a bit messy. Using available() works here because the underlying ByteArrayInputStream is guaranteed to have the entire array available - you won't see available() return 0 unless there really are no more bytes to read. However this is not the case for other types of streams - if you were reading from a socket for example, you'd have to allow that when available() == 0 it might just mean that the remaining bytes haven't been sent yet, for example. So be careful about using available() in other circumstances.
 
Gary Frick
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Jim for the suggestion. I'll play with this to see how it plays out. Gary
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oops, just noticed. If those integer values are stored using only two bytes, you can't use readInt() - you probably need readShort() or readUnsignedShort(). You can read the API for DataInputStream to see exactly what each one does. If it's not what you need exactly, don't overlook other methods - DataInputStream has a lot of different things it can do.
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic