> For the complete documentation index, see [llms.txt](https://valineliu.gitbook.io/deuterium-wiki/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://valineliu.gitbook.io/deuterium-wiki/reading/cs-jing-dian-shu-ji/csapp-3e-homework-solution/2.-representing-and-manipulating-information/2.78-divide-power-2.md).

# 2.78 Divide Power 2

★★

**Problem**:

Write code for a function with the following prototype:

```c
/* 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:

```c
#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;
}
```
