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?
Asked
Active
Viewed 2,563 times
2

template boy
- 10,230
- 8
- 61
- 97
-
http://stackoverflow.com/questions/4840410/how-to-align-a-pointer-in-c – simon Apr 28 '15 at 17:08
2 Answers
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
-
-
@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
-
4if 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