在Java中,是否有一个库可以将给定的字节序列(最好表示为十六进制)转换为给定InputStream的另一个字节序列?例如:
InputStream input = new FileInputStream(new File(...));
OutputStream output = new FileOutputStream(new File(...));
String fromHex = "C3BEAB";
String toHex = "EAF6"
MyMagicLibrary.translate(fromHex, toHex, input, output)
如果输入文件(十六进制看起来像)
00 00 12 18 33 C3 BE AB 00 23 C3 BE AB 00
翻译后的结果是
00 00 12 18 33 EA F6 00 23 EA F6 00
最佳答案
一旦我使用正则表达式做了类似的事情(用于简单地修补exe文件)。我将整个输入读入 byte[]
并使用 latin1 转换为字符串,然后进行替换并转换回来。虽然效率不高,但也没关系。您不需要正则表达式,简单的 String.replace 就可以了。
但就您而言,它可以非常简单且非常有效地完成:
int count = 0;
while (true) {
int n = input.read();
if (n == (fromAsByteArray[count] & 255)) {
++count;
if (count==fromAsByteArray.length) { // match found
output.write(toAsByteArray);
count = 0;
}
} else { // mismatch
output.write(fromAsByteArray, 0, count); // flush matching chars so far
count = 0;
if (n == -1) break;
output.write(n);
}
}
}
关于java - 翻译给定输入流的字节序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4749045/