cdivision

Division by power of 2 with round toward zero


I need to compute a number (a/(2**b) using only bitwise operators such as ! & ^ ~ and shifts. I was given the following hint but I'm new to C and I dont know what the code means:

int bias = x>0 ? 0 : ((1<<n)-1);

Can anyone explain it to me?

I thought a>>b would work but I dont think it works for negative numbers.


Solution

  • That particular bit of code gives you a bias of 0 if x is positive. Otherwise it produces a mask of the lower n bits. The x = a ? b : c; pattern is called the ternary operator(technically the 'conditional operator', apparently) in C.

    n      (1<<n)    (1<<n)-1     binary
    0        0x01       0x00     00000000
    1        0x02       0x01     00000001
    2        0x04       0x03     00000011
    3        0x08       0x07     00000111
    4        0x10       0x0F     00001111
    5        0x20       0x1F     00011111
    6        0x40       0x3F     00111111
    7        0x80       0x7F     01111111
               ...