Search code examples
c++alignment

How do I round to the next 32-bit alignment?


Packets coming over a network have padding bytes added at the end for alignment. I want to skip these bytes but the packet size is variable but known. Given a number n, how do I round it up to the next 4-byte alignment?


Solution

  • For any integer n and any stride k (both positive), you can compute the smallest multiple of k that's not smaller than n via:

    (n + k - 1) / k * k
    

    This uses the fact that integral division truncates.