Search code examples
javaarraysbytebyte-shifting

How to find out how long an array has to be when being initialized?


Imagine i have an byte-array ids.

Later i want to store data in it this way:

ids[cz << 24 | cx << 16 | y << 8 | z << 4 | x]

cz, cx, y, y, z, x are int values in this case.

So how long does the array need to be when i create it? I thought i would have to initialize the array this way:

byte[] ids = new byte[maxCz * maxCx * maxY * maxZ * maxX];

But it always gives me an ArrayIndexOutOfBoundsException.


Solution

  • The largest component in the OR-ed expression is cz << 24. Assuming that maxCz is 2k-1, and that the remaining max values are selected in a way for the bits of different components to not overlap, you need to allocate

    byte[] ids = new byte[(maxCz+1) << 24];
    

    When maxCz is 7, this is a 128 MB allocation, so the array is going to be very large.