C++ Representing a 3D array in a 1D array

后端 未结 2 1068
甜味超标
甜味超标 2021-01-05 13:02

I want to store the byte value of aFloat in pixelsArray for each 3D coordinate, in a 1D array:

float aFloat = 1.0;
unsigned char* pixelsArray = new unsigned          


        
相关标签:
2条回答
  • 2021-01-05 13:13

    Let's do this with a 2-dimensional array first:

    0            1      ... W-1
    W          W+1      ... 2*W-1
    2*W      2*W+1      ... 3*W-1
      .           .     .       .
      .           .      .      .
      .           .       .     . 
    (H-1)*W   (H-1)*W+1 ... H*W-1
    

    So you would accesss this with

    unsigned char* array = new unsigned char[H*W];
    for(int r=0;r<H;r++)
      for (int c=0; c<H; c++)
        array[r*w+c]=...;
    

    In your 3-dimensional array, you'd use

    i*WIDTH*3 + j*3 + k
    

    You do not need a sizeof(float) anywhere, though you probably need the value conversion that Mike DeSimone suggests.

    0 讨论(0)
  • 2021-01-05 13:19

    Your inside line needs to be:

    pixelsArray[(i * WIDTH + j) * 3 + k] = (unsigned char)(255.0 * aFloat);
    

    This should give you an all-white image.

    Make sure your target is really three bytes per pixel and not four (alpha channel or padding); if it is four, you'll just need to change the 3 above to a 4.

    0 讨论(0)
提交回复
热议问题