Sunday, August 10, 2014

Java Binary data parsing and packing

 I have published "yet another Java framework to parse and pack binary blocks"  (because I am too lazy to write tons of lines for different cases), I wanted some small compatible with JavaSE and Android solution so that meet the JBBP (Java Binary Block Parser).


   I will not be very verbose and just show how to pack and how to parse blocks with the framework

   Let’s imagine that we need parse some binary block which contains flag byte, data length represented as an unsigned short field and a byte array with the length defined in the second field, the code in the JBBP case will look like

JBBPParser.prepare(“byte flag; ushort length; byte [length] data;”);

The Parser returns some structure of parsed fields represented as inside objects and they can be reach through their names and/or field types but it is also too verbose thus I offer use the inside mapping to classes marked by a special annotation


@Bin class Parsed { byte flag; byte [] data; }
Parsed parsed = JBBPParser.prepare(“byte flag; ushort length; byte [length] data;”).parse(inputStream).mapTo(Parsed.class);


   Ok, I have shown how to parse the block, let me show how to pack a binary block, let’s make a binary block of the same format as we have parsed before with the some inside pseudo-DSL approach


JBBPOut.
        BeginBin(). 
           Byte(parsed.flag).
           Short(parsed.data.length).
           Byte(parsed.data).
        End().toByteArray();


   The Framework is compatible with Java 1.5+ platform and the Android platform, the project page is https://code.google.com/p/java-binary-block-parser/ and also the framework is accessible through the Maven central.

    You can take a look at some more complex test cases, for instance the case to parse a Java class with the JBBP https://code.google.com/p/java-binary-block-parser/source/browse/src/test/java/com/igormaznitsa/jbbp/it/ClassParsingTest.java

2 comments:

  1. Can I pack a 3 bytes field with JBBP?

    ReplyDelete
    Replies
    1. if just to write three bytes then it is possible just use standard approach
      final int b3 = 0x010203;
      JBBPOut.BeginBin().Byte(b3>>16,b3>>8,b3).End();
      if you want to unpack such field with JBBP script then you have to provide custom processor as in the example https://github.com/raydac/java-binary-block-parser/blob/master/src/test/java/com/igormaznitsa/jbbp/it/CustomThreeByteIntegerTypeTest.java
      if you want use such field as field in mapped class then you should mark the field as custom=true and provide JBBPMapperCustomFieldProcessor and JBBPCustomFieldWriter as in https://github.com/raydac/java-binary-block-parser/blob/master/src/test/java/com/igormaznitsa/jbbp/it/Z80_v1_ParsingTest.java

      Delete