I've got the following task:
Compute
x/(2^n)
, for0 <= 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?
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.
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 ...
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.
Pay close attention to the rounding behavior.
/
(integer divide) always rounds toward zero.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With