Re: pointer arithmetic for alignment on short or int boundry

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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



[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux