Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dividing by power of 2 using bit shifting

I've got the following task:

Compute x/(2^n), for 0 <= n <= 30 using bit shifting.

Requirement: Round toward zero.

Examples:

divpwr2(15,1) = 7
divpwr2(-33,4) = -2

Legal operators: ! ~ & ^ | + << >>

Maximum number of operators: 15

Here is what I've got so far:

public int DivideByPowerOf2(int x, int n)
{
    //TODO: find out why DivideByPowerOf2(-33,4) = -3 instead of -2
    return x >> n;
}

DivideByPowerOf2(15,1) = 7 is ok.

But DivideByPowerOf2(-33,4) = -3 instead of -2. Why?

like image 577
Sotelo Avatar asked Feb 21 '11 00:02

Sotelo


People also ask

How do you use bit shift to divide by 2?

When shifting right with a logical right shift, the least-significant bit is lost and a 0 is inserted on the other end. For positive numbers, a single logical right shift divides a number by 2, throwing out any remainders.

How do you divide by bit shifting?

To divide a number, a binary shift moves all the digits in the binary number along to the right and fills the gaps after the shift with 0: to divide by two, all digits shift one place to the right. to divide by four, all digits shift two places to the right. to divide by eight, all digits shift three places to the ...

How do you divide a number using bit manipulation?

Compute t = (N - D); . If (t >= 0) , then set the least significant bit of Q to 1, and set N = t . Left-shift N by 1. Left-shift Q by 1.


1 Answers

Pay close attention to the rounding behavior.

  • / (integer divide) always rounds toward zero.
  • What does bit shifting do?
  • How can you compensate for this difference?
like image 184
Ben Voigt Avatar answered Oct 09 '22 12:10

Ben Voigt