Last Updated: February 25, 2016
· dejnon

Bidirectional translation between 1D and 3D arrays

So I was doing some CUDA coding and wanted an interface for translating indices of 3D arrays (convenient to use but not suitable on GPU) and 1D "kernel" arrays (pain to decipher indexes but way faster then 3D).
In other words I wanted a relation that maps (i is the index in 1D):

(x,y,z) -> i

As well as:

i -> (x,y,z)

Here is what I used to get 1D index:

i = x + y * max_x + z * max_x * max_y

That was easy. Here is how it works the other way around:

x = i % max_x
y = ( i / max_x ) % max_y
z = i / ( max_x * max_y )

Note: max({x,y,z}) denotes the maximal possible value of the index i.e. the size of the sub-array (as in C's definition of arr[maxx][maxy][maxz]).

I actually worked out the math beneath it!

Say Thanks