我有一个偶数的长度的byte []数组。 现在,我希望byte []数组的前半部分的长度与byte []数组中的前两个字节一起作为字节b1,后两个字节b2等等。将byte []数组转换为字节数
请帮忙。 谢谢
我有一个偶数的长度的byte []数组。 现在,我希望byte []数组的前半部分的长度与byte []数组中的前两个字节一起作为字节b1,后两个字节b2等等。将byte []数组转换为字节数
请帮忙。 谢谢
这功课吗?我想你的主要问题是将成对的字节组合成双字节。这是通过什么叫做左移(<<
)实现的,该字节为8位,所以由8个移动:
int doubleByte = b1 + (b2 << 8);
请注意,我用b1
作为低字节,b2
为高字节。其余的很简单:分配一个长度为字节数组一半长度的int
的数组,然后迭代你的字节数组来构建新的int
数组。希望这可以帮助。
好,谢谢你们努力的朋友。例如:字节{130C00D2C00001}是我所拥有的。为了在13,0C和00上执行一些操作,我需要将它们分开。我想你现在在哪里清楚。 – sreekanthnu
对不起,此评论不是很有帮助。 – maksimov
也许我理解你的问题完全错误。
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.");
}
}
}
感谢您的努力,我的朋友。我得到了答案 – sreekanthnu
你的问题真的不是很清楚,我...尤其是你想怎么两个字节组合成一个... –
听起来功课给我。 –