Friday, January 6, 2012

Order of bitwise operation and ==

The following code was supposed to give the i-th bit of a 16bit integer:
However, get_ith(6, 0) gives us 1 instead of 0. Why?

It turns out that x&y==0 is interpreted as x & (y==0), which is 0 (false), thus 1 is returned instead. To fix the code, we should enclose x&y using parenthesis: if((x&y)==0). The correct code is the following:

No comments:

Visitors