最近項目中有一個地方需要處理多個byte[],將各byte[] 拼接,再做逐字節的校驗,就寫了一個類BytesUtil來處理它。
view plaincopy to clipboardprint?
package com.util;
/*******************************************************************************
*
* @author Spirit_demon
* @version 1.0
* @time 2009-12-21
*
*/
public class BytesUtil {
/***************************************************************************
*
* @param src1
* 保存的源byte[]
* @param src2
* 保存的源byte[]
* @return 將src1和src2拼接的byte
*/
public static byte[] addBytes(byte[] src1, byte[] src2) {
byte[] dest = new byte[src1.length + src2.length];
System.arraycopy(src1, 0, dest, 0, src1.length);
System.arraycopy(src2, 0, dest, src1.length, src2.length);
return dest;
}
/***************************************************************************
*
* @param maxlength
* 目標byte的max長度
* @param src
* 每一個byte[]
* @return 目標byte[]數組
*/
public static byte[] addBytes(int maxlength, byte[]... src) {
int length = 0; // 獲取每一byte數組的長
int index = 0; // 獲取複製到目標數組的起始點,
byte[] dest = new byte[maxlength]; // 目標數組
for (int i = 0; i < src.length; i++) {
length = src[i].length;
System.arraycopy(src[i], 0, dest, index, length); // 將每一個byte[]
// 複製到 目標數組
index = index + length; // 起始位置向後挪動byte[]的length
}
// 目標長度的數組不知道長度,在長度不足的情況下,會向後補0,
// 所以需要對得到的原始數組做一些處理
int count = 0;
for (int i = 0; i < dest.length; i++) {
if (dest[i] == 0) {
count++; // 統計原始數組補0的個數
}
}
byte[] result = new byte[100 - count]; // 生成新數組保存我們需要的值(非補0)
int pos = 0;
for (int i = 0; i < result.length; i++) {
if (dest[i] != 0) { // 判斷是非爲0,將不爲0的值保存
result[pos] = dest[i];
pos++;
}
}
return result;
}
// 測試類
public static void main(String[] args) {
byte[] a = { 1, 2 };
byte[] b = { 3, 4 };
byte[] c = { 8, 9 };
byte[] ax = { 4, 5 };
byte[] bx = { 7, 5 };
byte[] cx = { 4, 3 };
byte[] axx = { 4, 1 };
byte[] bxx = { 6, 9 };
byte[] cxx = { 8, 10 };
byte[] r = BytesUtil.addBytes(100, a, b, c, ax, bx, cx, axx, bxx, cxx);
System.out.println(java.util.Arrays.toString(r));
}
}
本篇文章來源於:開發學院 http://edu.codepub.com 原文鏈接:http://edu.codepub.com/2009/1221/18882.php