使用Java在二进制文件中搜索字节序列 [英] Searching for a sequence of Bytes in a Binary File with Java
本文介绍了使用Java在二进制文件中搜索字节序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字节序列,我必须使用Java在一组二进制文件中搜索。
I have a sequence of bytes that I have to search for in a set of Binary files using Java.
示例:我正在搜索字节序列<二进制文件中的code> DEADBEEF (十六进制)。
我如何用Java做这个?是否有内置方法,如二进制文件的 String.contains()
?
Example: I'm searching for the byte sequence DEADBEEF
(in hex) in a Binary file.
How would I go about doing this in Java? Is there a built-in method, like String.contains()
for Binary files?
推荐答案
不,没有内置方法可以做到这一点。但是,直接从 HERE 复制(已应用两个修复程序)到原始代码):
No, there is no built-in method to do that. But, directly copied from HERE (with two fixes applied to the original code):
/**
* Knuth-Morris-Pratt Algorithm for Pattern Matching
*/
class KMPMatch {
/**
* Finds the first occurrence of the pattern in the text.
*/
public int indexOf(byte[] data, byte[] pattern) {
int[] failure = computeFailure(pattern);
int j = 0;
if (data.length == 0) return -1;
for (int i = 0; i < data.length; i++) {
while (j > 0 && pattern[j] != data[i]) {
j = failure[j - 1];
}
if (pattern[j] == data[i]) { j++; }
if (j == pattern.length) {
return i - pattern.length + 1;
}
}
return -1;
}
/**
* Computes the failure function using a boot-strapping process,
* where the pattern is matched against itself.
*/
private int[] computeFailure(byte[] pattern) {
int[] failure = new int[pattern.length];
int j = 0;
for (int i = 1; i < pattern.length; i++) {
while (j > 0 && pattern[j] != pattern[i]) {
j = failure[j - 1];
}
if (pattern[j] == pattern[i]) {
j++;
}
failure[i] = j;
}
return failure;
}
}
这篇关于使用Java在二进制文件中搜索字节序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文