使用java中的规范解码二进制数据

时间:2011-08-16 10:43:58

标签: java

我有一个规范,告诉前四个字节引用一个特定的值,接下来的8个引用一个int,然后是32位,比如说一个特定的数据类型。 在java中读取此类数据的最佳方法是什么?有没有标准方法或者我只需要通过相应位置移动偏移来读取它

3 个答案:

答案 0 :(得分:4)

如果您真的需要在Java中执行此操作,最好的办法是创建一个带有自定义序列化的简单DTO。根据您的协议格式定义它的字段,并从字节流中读取它自己。类似的东西:

public class ProtocolDTO implements Serializiable {
    private int specificValue;
    private long anInt;
    private int particularDataType;

    // Constructors, Accessors

    private void readObject(ObjectInputStream in)
     throws IOException, ClassNotFoundException {
        specificValue = in.readInt();
        anInt = in.readLong();
        particularDataType = in.readInt();
    }
}

直接从这样的协议流中读取时要注意字节序。此外,您可能需要声明可序列化的子类型,具体取决于您的'specialDataType'是什么。

答案 1 :(得分:3)

要从流中读取基元类型,请使用DataInputStream并按顺序读取相应的类型。

http://download.oracle.com/javase/1.4.2/docs/api/java/io/DataInputStream.html

int i1 = stream.readInt();
long l1 = stream.readLong();

请注意验证流中使用的约定,即已签名或未签名等等。这可以在另一个答案中建议的反序列化方法中完成。

答案 2 :(得分:1)

Bit Masking会做