Question: I was curious to know how I can round a number to the nearest whole number. For instance, if I had:

```
int a = 59 / 4;

```

which would be 14.75 if calculated in floating point; how can I store the result as 15 in "a"?

Answer: 
Here's my solution. I like it because I find it more readable and because it has no branching (neither ifs nor ternaries).

```
int32_t divide(int32_t a, int32_t b) {
  int32_t resultIsNegative = ((a ^ b) & 0x80000000) >> 31;
  int32_t sign = resultIsNegative*-2+1;
  return (a + (b / 2 * sign)) / b;
}

```

Full test program that illustrates intended behaviour:

```
#include <stdint.h>
#include <assert.h>

int32_t divide(int32_t a, int32_t b) {
  int32_t resultIsNegative = ((a ^ b) & 0x80000000) >> 31;
  int32_t sign = resultIsNegative*-2+1;
  return (a + (b / 2 * sign)) / b;
}

int main() {
  assert(divide(0, 3) == 0);

  assert(divide(1, 3) == 0);
  assert(divide(5, 3) == 2);

  assert(divide(-1, 3) == 0);
  assert(divide(-5, 3) == -2);

  assert(divide(1, -3) == 0);
  assert(divide(5, -3) == -2);

  assert(divide(-1, -3) == 0);
  assert(divide(-5, -3) == 2);
}

```
Some alternatives for division by 4

```
return x/4 + (x/2 % 2);
return x/4 + (x % 4 >= 2)

```

Or in general, division by any power of 2

```
return x/y + x/(y/2) % 2;    // or
return (x >> i) + ((x >> i - 1) & 1);  // with y = 2^i

```

It works by rounding up if the fractional part ⩾ 0.5, i.e. the first digit ⩾ base/2. In binary it's equivalent to adding the first fractional bit to the result

This method has an advantage in architectures with a flag register, because the carry flag will contain the *last bit that was shifted out*. For example on x86 it can be [optimized into](https://reverseengineering.stackexchange.com/q/19735/2563)

```
shr eax, i
adc eax, 0

```

It's also easily extended to support signed integers. Notice that the expression for negative numbers is

```
(x - 1)/y + ((x - 1)/(y/2) & 1)

```

we can make it work for both positive and negative values with

```
int t = x + (x >> 31);
return (t >> i) + ((t >> i - 1) & 1);

```