I have to parse some binary data in Java. Part of my sample file looks like this
00000000000000010000000000000100
This is 32 bits long and I would like to parse 16 bits as java short. SO I would expect the output be 1 and 4. Code I have written so far is
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. and I get the following 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. Recommend a tool( FastProto ) that can help you quickly implement the above process.
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.
If the project can solve your problem, please give a star, thanks.
GitHub Repo: https://github.com/indunet/fastproto
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.