Maths in C/C++ - Rounding Query
Ok, so for a program I need to know two facts, the length of input and which highest number this length is closest to that is di开发者_如何学Govisible by 4. For example. If the length is 1, I want to record 4. If the length is 3, I want to record 4. If the length is 5, I want to record 8.
Mathematically I can divide the length by 4, this gives a decimal. If I round it up and times by 4 it gives me the answer I need. So, how do I get C to round up the contents of an int? I may be overcomplicating this so please say if I have missed something simple to do this.
Edit: I should add, I already know the length, this is something I would enter myself.
(length+3)/4*4
Overly-clever answer taking advantage of the fact that 4
is a power of two:
long rounded = length + 3 & -4UL;
(i + (4 - (i % 4)) % 4)
See http://ideone.com/zZ181 for a demonstration
The most intuitive answer given this is a power of 2 is (length+3) & ~3
(not ~4 as a previous answer suggested. We mask out the 1 and 2 bits having added 3).
精彩评论