【发布时间】:2020-08-14 18:38:08
【问题描述】:
已经有一个solution,但它涉及内存复制。我想要一个不涉及内存复制的解决方案。在这种情况下,保证输入字节数组 (byte[]) 必须包含 4 的倍数的字节数,以便可以将其转换为整数数组 (int[]) 而无需填充/重新分配。
这在 C 中很容易做到。我想要在 Java 中做类似的事情(特别是在 Android 上)。这是C版本:
// input byte array
// note that the number of bytes (char) is the multiple of 4 (i.e., sizeof(int)).
char* byte_array = calloc(100, sizeof(int));
byte_array[0] = 'a'; // 0x61
byte_array[1] = 'b'; // 0x62
byte_array[2] = 'c'; // 0x63
byte_array[3] = 'd'; // 0x64
// converting it to an integer array
// note that it does not involve memory copying
int* integer_array = (int *) byte_array;
// printing the first integer of the integer array
// it will print: 0x64636261 or 0x61626364, depending on the endianness
printf("0x%X\n", integer_array[0]);
真的可以在 Java 中做类似的事情(即不复制内存)吗?
【问题讨论】: