-1

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.

Fabian Schmidt
  • 304
  • 1
  • 11
  • Not knowing what `maxCz`, `maxCx`, `maxZ`, or `maxX` are, hard to help you here. – Scott Hunter Oct 20 '17 at 16:31
  • they represent the max values for cz, cx, x, y, z. for example: int cx = 7, int cz = 7, x = 16, y = 256, z = 16. – Fabian Schmidt Oct 20 '17 at 16:32
  • Which would be? – Scott Hunter Oct 20 '17 at 16:33
  • 1
    Array size must accommodate max potential index value, so simple version is `ids[(maxCz + 1) << 24]`. Complex version is `ids[(maxCz << 24 | maxCx << 16 | maxY << 8 | maxZ << 4 | maxX) + 1]`. In both cases, I assume the max values are inclusive. – Andreas Oct 20 '17 at 16:38

1 Answers1

1

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.

Sergey Kalinichenko
  • 675,664
  • 71
  • 998
  • 1,399