This post originated from an RSS feed registered with Java Buzz
by Wilfred Springer.
Original Post: Bit Syntax for Java (I)
Feed Title: Distributed Reflections of the Third Kind
Feed URL: http://blog.flotsam.nl/feeds/posts/default/-/Java
Feed Description: Anything coming to my mind having to do with Java
This is the same code, but then in Java, using Preon:
public class MpegHeader {
@BoundNumber(size="11", match="0b11111111111") private int frameSync;
@BoundNumber(size="2") private int mpegAudioVersionId;
@BoundNumber(size="2") private int layerDescription;
@Bound private boolean crcProtected;
@BoundNumber(size="4") private int bitRateIndex;
@BoundNumber(size="2") private int sampleRateFrequencyIndex;
@Bound private boolean padded;
@Bound private boolean privateBit;
@BoundNumber(size="2") private int channelMode;
@BoundNumber(size="2") private int modeExtension;
@Bound private boolean copyright;
@Bound private boolean original;
@BoundNumber(size="2") private int emphasis;
}
Codec codec = new Codecs.create(MpegHeader.class); Codecs.decode(codec, buffer);
Now, there are obviously a lot of differences. The Erlang example also includes calls to functions defined elsewhere to determine the bitrate and frame lenght. The Preon example wouldn't have that. If you would need that, you could imagine implementing it as methods of the MpegHeader class.
Also note that the example does match on the first 11 bits, expecting them to be ones only. The notation @BoundNumber(size="11", match="0b11111111111") basically says that this field will be decoded from 11 input bits, as long as it matches the bit pattern "11111111111". Or to be more precise, as long as it matches the numeric value of 11 "1" bits, interpreted as an integer. If that criterion isn't match, the Codec will throw a DecodingException.
I will try to work the other examples into Java with Preon examples as well, but it's interesting to see how the two approaches compare. What would you prefer? And why?