Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fast increase number to be mod 16 in C

what is the best way to to get the closest, non-smaller 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);
}

the expected results are

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

etc

like image 870
Aviad Rozenhek Avatar asked Dec 05 '22 21:12

Aviad Rozenhek


1 Answers

int non_smaller_int_divisible_by_16(int x)
{
  return (x + 15) & ~15;
}

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

Edit:

It's not clear what you want to happen with negative numbers - both your and my code will round to more-positive values (ie negative numbers will get smaller). If negative values don't make sense in your program, it'd be better to use an unsigned type.

Finally, you might be interested to look at Bit Twiddling Hacks, which is a great collection of some really clever (if often extremely obscure) tricks along these lines.

like image 113
John Carter Avatar answered Dec 20 '22 13:12

John Carter