简体   繁体   English

如何将1D数组转换为3D数组?

[英]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. 我有一个由4096(16 ^ 3)个字节组成的文本文件,需要加载并放入3D数组中。 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? 每个字节代表一个16 ^ 3块中的图块ID,那么如何基于长度,宽度和深度为16的1D数组创建一个3D数组呢? 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. 我不明白,考虑到我是计算x,y和z变量的变量。

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: 使用您给出的第一个公式,从一组xyz到一维数组中的相应索引,如下所示:

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. 根据数据的组织方式(例如,按层,按行,按列,按列,按列,按层,按行,按行,按列,按层等),您可能会需要在计算索引到data数组时切换xyz的顺序。

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 参见http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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