简体   繁体   English

Java 解析二进制数据

[英]Java parsing binary data

I have to parse some binary data in Java. Part of my sample file looks like this我必须解析 Java 中的一些二进制数据。我的示例文件的一部分如下所示

00000000000000010000000000000100

This is 32 bits long and I would like to parse 16 bits as java short.这是 32 位长,我想将 16 位解析为 java 短。 SO I would expect the output be 1 and 4. Code I have written so far is所以我希望 output 是 1 和 4。到目前为止我写的代码是

Path path = Paths.get("filePath");
byte[] b = Files.readAllBytes(path);

ByteBuffer buffer = ByteBuffer.wrap(b).order(ByteOrder.LITTLE_ENDIAN);
    buffer.rewind();
    ShortBuffer ib = buffer.asShortBuffer();
     System.out.println(b.length);
     System.out.println(ib.get());
     System.out.println(ib.get());

This is parsing each value a ascii.这是将每个值解析为 ascii。 and I get the following output.我得到以下 output。

32
12336
12336

Can someone help me with this.有人可以帮我弄这个吗。

Thanks AM谢谢上午

Solved parsing the String 解决了解析字符串

    Path path = Paths.get("filePath");
    List<String> lines = null;
    try {
        lines = Files.readAllLines(path);
    } catch (IOException e) {
        e.printStackTrace();
    }

    for (String line : lines) {
        System.out.println(Short.parseShort(line.substring(0, 16), 2));
        System.out.println(Short.parseShort(line.substring(16, 32), 2));
    }

According to your description, the binary data contains 2 fields, both of which are signed 16-bit int, and are stored in little-endian.根据你的描述,二进制数据包含2个字段,都是有符号的16位int,并以little-endian存储。 Recommend a tool( FastProto ) that can help you quickly implement the above process.推荐一个工具( FastProto ),可以帮助你快速实现上面的过程。

import org.indunet.fastproto.annotation.*;

@DefaultEndian(EndianPolicy.Little)
public class MyData {
    @Int16Type(offset = 0)
    Short s1;
 
    @Int16Type(offset = 2)
    Short s2;
}


byte[] binary = ... // your binary

MyData data = FastProto.parse(binary, MyData.class);

System.out.println(data.s1); // output 1
System.out.println(data.s2); // output 4

Maybe you have noticed that FastProto describes the field information in binary data through annotations, which is very simple and efficient.或许你已经注意到,FastProto 通过注解来描述二进制数据中的字段信息,非常简单高效。

If the project can solve your problem, please give a star, thanks.如果项目能解决您的问题,请给个star,谢谢。

GitHub Repo: https://github.com/indunet/fastproto GitHub 回购: https ://github.com/indunet/fastproto

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM