Saturday, October 13, 2012

Align a pointer to 4 byte boundary, Align a pointer to word bounday

Many a times, you would need to move a pointer to next word aligned location.

The pointer you are getting is not word align.


uint8 alignBoundary =4; //can be 2 or 8 too


void SomeFun(uint8 *ptr)
{
        uint8 misAlignBytes;
        uint8 shiftRequired;

        misAlignBytes = ptr & (alignBoundary-1);
        //e.g  in case of 4 byte align above would be misAlignBytes = ptr & 0x03

        shiftRequired = (misAlignBytes ? (alignBoundary- misAlignBytes ):0 ) ;

       ptr = ptr + (uint8*)shitRequired;

      //thats it you pointer is word aligned.
      //After this pointer you can use your pointer without being worried about misalignment 

}



 

No comments: