Using C struct in Java

后端 未结 5 772
情歌与酒
情歌与酒 2020-12-15 08:19

I have to code a Java program that will receive messages from network and display their content to the user. The problem is that the messages that I receive are simply binar

5条回答
  •  感情败类
    2020-12-15 08:51

    There is a library called Preon that was designed to help you with this type of task: Preon site Basically, they try to keep all the logic for reading your pojo's from the binary stream in annotations tied to each field in your pojo.

    An example from their docs where you control the size of the int you are reading:

    class Rectangle
    {
      @BoundNumber(size="16") private int x1;
      @BoundNumber(size="16") private int y1;
      @BoundNumber(size="16") private int x2;
      @BoundNumber(size="16") private int y2;
    }
    

    or to specify endianness:

    class Rectangle
    {
      @BoundNumber(byteOrder=LittleEndian) private int x1;
      @BoundNumber(byteOrder=LittleEndian) private int y1;
      @BoundNumber(byteOrder=LittleEndian) private int x2;  
      @BoundNumber(byteOrder=LittleEndian) private int y2;
    }
    

    You can even use mini-equations with references to values in previous fields to specify size / length, etc.

    @BoundList(size="width * height") byte[] pixels;
    @BoundNumber(size="nrBits * 2") int value;
    

    Oh, and they also offer conditional logic, all in annotations.

提交回复
热议问题