title: BMP color replacer: Algorithm for padding doesn't work
body: <p>I am building a function that replaces a color in a BMP image with another target color.
  It works as long as I don't attempt to replace a color in image that requires padding.
  However, I am almost certain that the way I account padding is correct.. So for me this is a complete mystery.</p>
  <hr />
  <p><img src="https://i.stack.imgur.com/8xLAl.png" alt="enter image description here" /></p>
  <hr />
  <p><em>330 x 250 (248 054 bytes) Hi-color 24bit bitmap</em></p>
  <hr />
  <p>This is the function:</p>
  <pre><code>union
  {
      unsigned long ulColor;
      unsigned char byteColor[4];
  } oldColor;
  union
  {
      unsigned long ulColor;
      unsigned char byteColor[4];
  } newColor;
  
  typedef unsigned char           BYTE;
  typedef unsigned short int      WORD;
  typedef unsigned long int       DWORD;
  typedef unsigned long long int  DDWORD;
  
  DDWORD
  bitfox_color_replace_data
  (BYTE *buff, BYTE old_r, BYTE old_g, BYTE old_b, BYTE new_r, BYTE new_g, BYTE new_b)
  {
      #define OFFSET_OF_SIZE      0x2
      #define OFFSET_OF_PIXELS    0xA
      #define OFFSET_OF_WIDTH     0x12
      #define OFFSET_OF_HEIGHT    0x16
  
      DWORD* buffSize     = (DWORD*)&amp;buff[OFFSET_OF_SIZE];
      DWORD* buffPixels   = (DWORD*)&amp;buff[OFFSET_OF_PIXELS];
      DWORD* buffWidth    = (DWORD*)&amp;buff[OFFSET_OF_WIDTH];
      DWORD  buffHeight   = 0;
  
      BYTE pad            = 0;
      
      DDWORD pixels_replaced = 0;
      DDWORD i;
  
      oldColor.byteColor[0] = old_b;  newColor.byteColor[0] = new_b;
      oldColor.byteColor[1] = old_g;  newColor.byteColor[1] = new_g;
      oldColor.byteColor[2] = old_r;  newColor.byteColor[2] = new_r;
      
      for(i = (*buffPixels); i &lt; (*buffSize); i += 3)
      {
          if( i == ((*buffPixels) + (((*buffWidth) * 3) + pad) * (buffHeight + 1)) )
          {
              pad = ((*buffWidth) % 4);
              buffHeight++;
              i += pad;
          }
          
          if(!memcmp(buff + i, oldColor.byteColor, 3))
          {
              memcpy(buff + i, newColor.byteColor, 3);
  
              pixels_replaced++;
          }
  
      }
      return pixels_replaced;
  }
  </code></pre>
  <p>What am I possibly doing wrong ?</p>