How to parse byte[] (including BCD coded values) to Object in Java

733 Views Asked by At

I'd like to know if there is a simple way to "cast" a byte array containing a data-structure of a known layout to an Object. The byte[] consists of BCD packed values, 1 or 2-byte integer values and character values. I'm obtaining the byte[] via reading a file with a FileInputStream.

People who've worked on IBM-Mainframe systems will know what I mean right away - the problem is I have to do the same in Java.

Any suggestions welcome.

2

There are 2 best solutions below

0
On BEST ANSWER

No, because the object layout can vary depending on what VM you're using, what architecture the code is running on etc.

Relying on an in-memory representation has always felt brittle to me...

I suggest you look at DataInputStream - that will be the simplest way to parse your data, I suspect.

0
On

Not immediately, but you can write one pretty easily if you know exactly what the bytes represent.

To convert a BCD packed number you need to extract the two digits encoded. The four lower bits encode the lowest digit and you get that by &'ing with 15 (1111 binary). The four upper bits encode the highest digit which you get by shifting right 4 bits and &'ing with 15.

Also note that IBM most likely have tooling available if you this is what you are actually doing. For the IBM i look for the jt400 IBM Toolbox for Java.