上下求索
【原创】Java中Byte字节流处理的自定义方法库1
上一篇 /
下一篇 2010-07-13 09:44:16
1.将不同的byte[]字节数组流打包成一个字节数组
public static byte[] pack(byte[]... agrs) {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
for(byte[] b:agrs){
if(b!=null){
try {
bout.write(b);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
continue;
}
byte[] buff = bout.toByteArray();
return buff;
}
2.在byte字节流中搜索指定字节流的位置,采用KMP算法实现。
/**取到字节流中指定字节流的位置
* The Knuth-Morris-Pratt Pattern Matching Algorithm can be used to search a byte array.
* Search the data byte array for the first occurrence
* of the byte array pattern.
*/
public static int indexOf(byte[] data, byte[] pattern) {
int[] failure = computeFailure(pattern);
int j = 0;
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 + 1;
//return i - pattern.length + 1;
}
}
return -1;
}
/**
* Computes the failure function using a boot-strapping process,
* where the pattern is matched against itself.
*/
private static 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;
}
3.将字节流的详细信息显示
//HEX字节流显示
public static String dumpBytesAsHEX(byte[] bytes) {
int idx = 0;
String s = "";
StringBuilder body = new StringBuilder();
for (int i=0;i<1024&&i<bytes.length;i++) {
byte b = bytes[i];
int hex = ((int) b) & 0xff;
String shex = Integer.toHexString(hex).toUpperCase();
if (1 == shex.length()) {
body.append("0");
}
body.append(shex);
body.append(" ");
idx++;
// if (16 == idx) {
// s = body.toString();
// body = new StringBuilder();
// idx = 0;
// }
}
if (idx != 0) {
s = body.toString();
}
return s;
}
收藏
举报
TAG:
java
Java
JAVA