tags:

views:

160

answers:

2

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.

+3  A: 

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
           ...
jkerian
In spite of that wiki page's description, I don't think I've ever heard anyone call ?: the 'conditional operator', it's always been the 'ternary operator', at least whenever anyone's known what to call it at all.
jkerian
It'll probably continue to be called the "ternary operator" til someone comes up with a new ternary operator. Then the term will be confusing. "Conditional operator", however, will remain unambiguous.
cHao
I don't really get the otherwise part. Say if n = 5, then the variable bias = 00011111 in binary?
Dan
@jkerian: [C99](http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf) calls it the "conditional operator" - § 6.5.15.
Matthew Slattery
@Dan: yes, if n=5 bias will be set to 11111 (leading zeroes depends on the variable size, of course)
jkerian
A: 

well,x<<n works correctly for positive numbers. so why dont you just use something like result=if sign=1 then (x<<n) else(-x<<n) (replace the iftehenelse by some masking with the sign bit)

thing