views:

638

answers:

1
+2  Q: 

Bit packing in C

I'm trying to convert an RGB image to an ARGB image, basically just adding 255 in for the alpha channel. I was wondering if there is any pack method to do this without iteration? So to iterate over my RGB data and append the 255 to each pixel.

+3  A: 

C doesn't have "methods" ... And no, this doesn't sound like anything there's a routine for in the standard library. I think you need to code it yourself, using something like this:

void setAlpha(unsigned char *rgba, int width, int height, int alpha)
{
  int x, y;

  for(y = 0; y < height; y++)
  {
    for(x = 0; x < width; x++, rgba += 4)
    {
      rgba[3] = (unsigned char) alpha;
    }
  }
}

Basic assumptions:

  • Packing order is RGBA in memory, i.e. the offset is 3 to the alpha byte, from the start of the pixel.
  • Image is stored with the top-left pixel at the initial address, in right-to-left, top-to-bottom order.
  • There is no padding or anything

Also note order of loops; this can make a huge difference to real-world performance due to caching. This code touches pixels that are close in memory in sequence, which is good called "good locality".

Changing the pointer to point at the next pixel rather than stating the address (rgba[4 * y * width + 4 * x + 3]) is also an optimization, and (to me) easy enough to understand.

unwind
that's pretty much what I had anyway, but cuts down on the variables a little. Thanks for the help