pointer arithmetic for alignment on short or int boundry

Eljay Love-Jensen eljay@adobe.com
Sun Sep 21 15:40:00 GMT 2003


Hi Andy,

You need to do mathematical operations on non-pointer types.  Use <stdint.h> (part of C99) to assist.

char* alignToIntPtr(char* a) {
  const int lowBitsMask = sizeof(int) - 1;
  int lowBits = reinterpret_cast<intptr_t>(a) & lowBitsMask;

  // Rounding UP to next appropriate address, or stay same.
  int delta = lowBits ? (sizeof(int) - lowBits) : 0;
  a += delta;

  // ...OR...
  // Rounding DOWN to previous appropriate address, or stay same.
  a -= lowBits;

  return a;
}

I trust the optimizer to make the actual code nice and efficient.  However, if this is in a really tight loop (as indicated by the profiler), you may want to investigate some bit-twiddling algorithms to make it even more efficient.

HTH,
--Eljay




More information about the Gcc-help mailing list