Treating a 1D array as 2d (Bitmaps etc)

This is purely a quick note for me more than anything as I always forget which way around to do this.

Essentially binary data (such as bitmaps) are stored in a 1D array and this is a common method in which to access the data, I won’t be detailing anything about locking memory or memory management at all, I may deal with the ‘stride’ situation though(the width of a single row of data) . Just the accessing algorithm.

If we have an image that’s 800 x 600 pixels in size we could use a loop to iterate through it like so

//Pseudo C# / C++ for simple 1d/2d array access.
const int width = 800;
const int height = 600;
byte* firstPos = &imageData;
bool[] hasPix = new bool[width*height]
for(int y =0; y < height; y++)
  {
    for(int x =0; x < width; x++)
      {
        byte* data = firstPos  + (x + y * width);
      }
  }

/Say we have actual bitmap data, so RGBA for example (in this case the struct is BGRA
//format 0x26200A

static int bitsPerPixel = 20; //(0x26200a & ff00) >> 8
static int bytesPerPixel = 32; // 4 = (20 + 8) / 8
static int stride = 4800; // ((width * bpp + 3) / 4);
// that's how the math should be, but when I ran this in c# it used different numbers based up on the System.Drawing Image class... So I've gone with that.


for(int y =0; y < height; y++)
{
for(int x =0; x < width; x++)
{
byte* d= firstPos + y * stride + x * bytesPerPixel / 8byte b = d[0];
byte g = d[1];
byte r = d[2];
byte a = d[3];
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.