Forums Register Login

extracting bytes from byte array

+Pie Number of slices to send: Send
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?
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
Thanks Jim for the suggestion. I'll play with this to see how it plays out. Gary
+Pie Number of slices to send: Send
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.
You guys haven't done this much, have ya? I suggest you study this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 5132 times.
Similar Threads
Need Help With: java.io StreamCorruptedException invalid stream header
How to upload a byte array into BLOB column?
Inserting Image into Oracle.
Saving Japanese Characters in Oracle Blob using Java program
Conversion Blob to Byte Array
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 02:41:37.