Java,如何从字节数组中获取字节集合
Java, how to get a collection of byte from a byte array
这个问题可能看起来很独特,但我很难解决它。
我有一个字节数组(每行一个 DW)并尝试获取每 9 个字节的字节值。
字节数组如下所示:
0 1 2 3
4 5 6 7
8| 9 10 11
12 13 14 15
16 17| 18 19
20 21 22 23
24 25 26| 27
28 29 30 31
32 33 34 35|
.......
这是我需要用来从上述专利中获取值的已定义函数:
getValue(int DWOffset, int highBit, int lowBit)
//DWOffset indicates the row of the data.
//highBit indicates the ending bit
//lowBit indicates the starting bit
我的问题是如何使用for循环从数据中(出现|的地方)获取每9个字节?可以使用
找出数据长度
data.getLength(); //which returns the total number of bytes in the data
到目前为止,我可以得到前两行的值:
for(int i = 0; i < data.getLength()/(4*2); i++){
getValue(i*2, 31, 0); //DW i
getValue(i*2 + 1, 31, 0); //DW i+1
}
部分问题在于您似乎在混合范例,从概念上将其视为二维和一维数组。将其视为二维,您需要一个 returns 单个字节的 getValue(int row, int column)。然后你可以这样做:
final int TOTAL_BYTES_TO_INCLUDE = 9;
byte[] byteArray[] = new byte[TOTAL_BYTES_TO_INCLUDE];
int arrayIndex = 0;
for (int r = 0; r++; r < number_of_rows) {
for (int c = 0; c++; c < 4) {
byteArray[arrayIndex++] = getValue(r, c);
if (arrayIndex >= TOTAL_BYTES_TO_INCLUDE) {
... do something with your byte array ...
arrayIndex = 0;
}
}
}
有一些极端情况需要处理,比如如果可用值的数量不是 9 的倍数,会发生什么。如果读入的值导致字节溢出会发生什么。我不会在每次迭代之前重新初始化数组,但是否存在遗留某些东西的风险。
这个问题可能看起来很独特,但我很难解决它。
我有一个字节数组(每行一个 DW)并尝试获取每 9 个字节的字节值。 字节数组如下所示:
0 1 2 3
4 5 6 7
8| 9 10 11
12 13 14 15
16 17| 18 19
20 21 22 23
24 25 26| 27
28 29 30 31
32 33 34 35|
.......
这是我需要用来从上述专利中获取值的已定义函数:
getValue(int DWOffset, int highBit, int lowBit)
//DWOffset indicates the row of the data.
//highBit indicates the ending bit
//lowBit indicates the starting bit
我的问题是如何使用for循环从数据中(出现|的地方)获取每9个字节?可以使用
找出数据长度data.getLength(); //which returns the total number of bytes in the data
到目前为止,我可以得到前两行的值:
for(int i = 0; i < data.getLength()/(4*2); i++){
getValue(i*2, 31, 0); //DW i
getValue(i*2 + 1, 31, 0); //DW i+1
}
部分问题在于您似乎在混合范例,从概念上将其视为二维和一维数组。将其视为二维,您需要一个 returns 单个字节的 getValue(int row, int column)。然后你可以这样做:
final int TOTAL_BYTES_TO_INCLUDE = 9;
byte[] byteArray[] = new byte[TOTAL_BYTES_TO_INCLUDE];
int arrayIndex = 0;
for (int r = 0; r++; r < number_of_rows) {
for (int c = 0; c++; c < 4) {
byteArray[arrayIndex++] = getValue(r, c);
if (arrayIndex >= TOTAL_BYTES_TO_INCLUDE) {
... do something with your byte array ...
arrayIndex = 0;
}
}
}
有一些极端情况需要处理,比如如果可用值的数量不是 9 的倍数,会发生什么。如果读入的值导致字节溢出会发生什么。我不会在每次迭代之前重新初始化数组,但是否存在遗留某些东西的风险。