Rapid increase in number to be mod 16 in C

What is the best way to get the closest, at least, number that is divisible by 16?

The method I came up with doesn’t look very elegant or fast.

int non_smaller_int_divisible_by_16(int x) { return x + ((16 - (x % 16)) % 16); } 

Expected results

 result | X values -------|---------- 16 | 1,2,..., 16 32 | 17, 18, ... 32 48 | 33, 34, ..., 48 

etc.

+4
source share
4 answers

after @nemo's comment, there is a great way to solve this problem, which works for all mods, is very readable and should be fast

 unsigned int non_smaller_int_divisible_by_16(unsigned int x) { return x + ((-x) % 16); } 

therefore the general version

 unsigned int non_smaller_int_divisible_by_base(unsigned int x, unsigned int base) { return x + ((-x) % base); } 
+1
source
 int non_smaller_int_divisible_by_16(int x) { return (x + 15) & ~15; } 

Since 16 is the power of two, you can use binary masking - add 15 so we get the next highest multiplier and a mask with a bitwise inversion of 15 to clear the lower bits.

Edit:

It is not clear what you want to do with negative numbers - both your and my code will be rounded up to more positive values ​​(i.e. negative numbers will decrease). If negative values ​​do not make sense in your program, it would be better to use an unsigned type.

Finally, you might be interested to watch Bit Twiddling Hacks , which is an excellent collection of some really smart (if often extremely obscure) tricks along these lines.

+11
source

@therefromhere's solution is more elegant and faster, but if you need to do this with a number that is not a power of 2, you can use this approach.

 int non_smaller_int_divisible_by_n(int x, int n) { return n*((x+n-1)/n); } 
+5
source
 int non_smaller_int_divisible_by_16(int x) { return (x & 15) ? (x | 15) + 1 : x; } 
-1
source

All Articles