There is already a solution but it involves memory copying. I want a solution that does not involve memory copying. In this scenario, it is guaranteed that the input byte array (byte[]
) must consist of the number of bytes being the multiple of 4 so that it can be converted to an integer array (int[]
) without padding/reallocation.
This is very easy to do in C. I want the similar thing in Java (specifically on Android). Here is the C version:
// 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]);
Is it really possible to do the similar thing (i.e., no memory copying) in Java?