我有一个byte []数组,偶数个长度。 现在,我希望byte []数组突破其长度的一半,byte []数组中的前两个字节为字节b1,接下来两个为字节b2,依此类推。
请帮忙。 感谢
答案 0 :(得分:0)
这是家庭作业吗?我想你的主要问题是将字节对组合成双字节。这是通过所谓的左移(<<
)来实现的,字节是8位,因此移位8:
int doubleByte = b1 + (b2 << 8);
注意,我使用b1
作为低位字节,b2
作为高位字节。
其余的很简单:分配一个int
数组,其长度是字节数组的一半,然后遍历字节数组以构建新的int
数组。希望这会有所帮助。
答案 1 :(得分:0)
也许我完全理解你的问题。
public class Main {
// run this
public static void main(String[] args) {
// create the array and split it
Main.splitArray(new byte[10]);
}
// split the array
public static void splitArray(byte[] byteArray) {
int halfSize = 0; // holds the half of the length of the array
int length = byteArray.length; // get the length of the array
byte[] b1 = new byte[length / 2]; // first half
byte[] b2 = new byte[length / 2]; // second half
int index = 0;
if (length % 2 == 0) { // check if the array length is even
halfSize = length / 2; // get the half length
while (index < halfSize) { // copy first half
System.out.println("Copy index " + index + " into b1's index " + index);
b1[index] = byteArray[index];
index++;
}
int i = 0; // note the difference between "i" and "index" !
while (index < length) { // copy second half
System.out.println("Copy index " + index + " into b2's index " + i);// note the difference between "i" and "index" !
b2[i] = byteArray[index];// note the difference between "i" and "index" !
index++;
i++; //dont forget to iterate this, too
}
} else {
System.out.println("Length of array is not even.");
}
}
}