如何将下面的java代码转换为等效的dart。
private static final byte[] mIdBytes = new byte[]{(byte) 0x01, (byte) 0x02, (byte) 0x03, (byte) 0x7E};
byte[] data;
System.arraycopy(mIdBytes, 2, data, 0, 4);
有没有Dart方法可以进行类似的操作?
我在调查这个:https://pub.dev/documentation/ckb_dart_sdk/latest/ckb-utils_number/arrayCopy.html
匹配Java的System.arrayCopy(source, sourceOffset, target, targetOffset, length)
你应该使用
target.setRange(targetOffset, targetOffset + length, source, sourceOffset);
这比对某些列表使用List.copyRange
更有效,例如在具有相同元素大小的类型化数据列表之间进行复制(如两个Uint8List
(。
好吧,我找到了方法。你可以直接使用
List.copyRange(data, 0, mIdBytes, 2);
这是我在您的案例中发现的一种变通方法。这被称为sublist((,此方法将采用start index
和end index
。
IDEA:
- 使用
sublist()
,并复制要启动的元素,即sourcePos=you_pos- 源阵列将像
sourceArray.sublist(startIndext, endIndex)
一样使用- 目标数组将使用sublist((的值进行初始化
end index+2
中会提到项目应该添加到什么长度,因为它会忽略最后一个项目,并复制到索引-1
最终代码
void main() {
List<int> source = [1, 2, 3, 4, 5, 6];
List<int> target = [];
int startPos = 1;
int length = 4;
// to ensure the length doesn't exceeds limit
// length+2 because, it targets on the end index, that is 4 in source list
// but the end result should be length+2 to contain a length of 5 items
if(length+1 <= source.length-1){
target = source.sublist(startPos, length+2);
print(target);
}else{
print('Cannot copy items till $length: index out of bound');
}
}
//OUTPUT
[2, 3, 4, 5, 6]