2.78 Divide Power 2

★★

Problem:

Write code for a function with the following prototype:

/* Divide by power of two. Assume 0 <= k < w-1 */
int divide_power2(int x, int k);

The function should compute x/2^k with correct rounding.

Code:

#include <stdio.h>
#include <assert.h>
#include <limits.h>

int divide_power2(int x, int k) {
    /*
     * if x >= 0, then the result is x >> k;
     * if x < 0, we should add x with bias to make sure the correct rounding.
     *         (x + (x + (1 << k) - 1)) >> k
     */
    int neg_flag = x & INT_MIN;
    neg_flag && (x = x + (1 << k) - 1);
    return x >> k;
}

int main() {
    assert(divide_power2(7, 2) == 1);
    assert(divide_power2(-7, 2) == -1);
    return 0;
}

Last updated