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


   The Framework is compatible with Java 1.5+ platform and the Android platform, the project page is 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


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

    1. if just to write three bytes then it is possible just use standard approach
      final int b3 = 0x010203;
      if you want to unpack such field with JBBP script then you have to provide custom processor as in the example
      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