简体   繁体   中英

How do I convert a 1D array to a 3D array?

I have a text file composed of 4096 (16^3) bytes that I need to load up and throw into a 3D array. Each byte represents a tile ID in a 16^3 chunk, so how can I create a 3D array based off a 1D array with 16 length, width and depth? I know the algorithm is something like this:

i = x + WIDTH * (y + HEIGHT * z);


z = Math.round(i / (WIDTH * HEIGHT));
y = Math.round((i - z * WIDTH * HEIGHT) / WIDTH);
x = i - WIDTH * (y + HEIGHT * z);

How do I find i though? I don't understand, considering i is a variable in calculating the x, y, and z variables.

You can do it with three nested loops. Use the first formula that you give to go from a set of x , y , and z to the corresponding index in the 1D array, like this:

byte[] data = ... // Read 4096 bytes
byte[][][] res = new byte[16][16][16];
for (int x = 0 ; x != 16 ; x++) {
    for (int y = 0 ; y != 16 ; y++) {
        for (int z = 0 ; z != 16 ; z++) {
            res[x][y][z] = data[16*16*x + 16*y + z];
        }
    }
}

Depending on the way your data is organized (eg by layer, then by row, than by column, or by column, then by layer, then by row, or by row, then by column, then by layer, etc.) you might need to switch the order of x , y , and z in the computation of the index into the data array.

try this

    byte[][][] a = new byte[16][16][16];
    InputStream is = new FileInputStream("file");
    for(int i = 0; i < 16; i++) {
        for(int j = 0; j < 16; j++) {
            is.read(a[i][j]);
        }
    }

see http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM