Search code examples
c++mathbitwise-operators

How to calculate nearest bigger integer divisible by 8 in C++ bitwise operation?


I need to calculate the nearest bigger integer devisible by 8. For examples:

  1. for a=0, the nearest bigger integer devisible by 8 is 0.
  2. for from a=1 to a=7, the nearest bigger integer devisible by 8 is 8.
  3. for a=8, the nearest bigger integer devisible by 8 is 8.
  4. for from a=x*8+1 to a=x*8+7, the nearest bigger integer devisible by 8 is a=(x+1)*8.
  5. for a=x*8, the nearest bigger integer devisible by 8 is a=x*8 itself.

How should I implement this function int nearestBiggerIntegerDevisibleBy8(int a) in C++ bitwise operation (fastest)?


Solution

  • This one way to go about it

    #include <stdio.h>
    
    int nearestBiggerInt(int n){ 
        n += 7;
        return (n & ~7);
    }
    
    int main()
    {
        for (int i = 0; i < 20; i++)
            printf("%d -> %d\n", i, nearestBiggerInt(i));
        return 0;
    }
    

    Output

    0 -> 0
    1 -> 8
    2 -> 8
    3 -> 8
    4 -> 8
    5 -> 8
    6 -> 8
    7 -> 8
    8 -> 8
    9 -> 16
    10 -> 16
    11 -> 16
    12 -> 16
    13 -> 16
    14 -> 16
    15 -> 16
    16 -> 16
    17 -> 24
    18 -> 24
    19 -> 24