2

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?

template boy
  • 10,230
  • 8
  • 61
  • 97

2 Answers2

7

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.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • So for 4-byte alignment it would be `(n + 32 - 1) / 32 * 32`? – template boy Apr 28 '15 at 17:04
  • @templateboy: If you're counting in bits, yes, though that's pretty unlikely. You should probably count in bytes, i.e. in the size of the smallest allocatable (and hence alignable) unit of storage. – Kerrek SB Apr 28 '15 at 17:08
0

Another version. n is the number you want to alight to 4 (say k). Formula would be=n+k-n%k (where % is modulus)

For example (in Unix bc calculator)

k=4
n=551
n+k-n%k
552

to check that it is aligned:

scale=4
552/4
138.0000
Madars Vi
  • 947
  • 9
  • 12
  • 4
    if n is already aligned this adds an extra k: e.g. n=4; k=4; 4+4-(4%4)= 8, not 4. it works, if you check n%k != 0 first, but in some code there are penalties for taking a branch and @Kerrek SB's solution is preferred. – Brad May 31 '20 at 00:31