What does i+=(i&-i) do? Is it portable?

  • A+
Category:Languages

Let i be a signed integer type. Consider

i += (i&-i); 

where initially i>0.

  1. What does this do? Is there an equivalent code using arithmetic only?
  2. Is this dependent on a specific bit representation of negative integers?

Source: setter's code of an online coding puzzle.

 


That expression i & -i is based on Two's Complement being used to represent negative integers. Simply put, it returns a value k where each bit except the least significant bit is set to 0, but that least significant bit keeps its own value. (i.e. 1)

As long as the expression you provided executes in a system where Two's Complement is being used to represent negative integers, it would be portable. So, the answer to your second question would be that the expression is dependent on the representation of negative integers.

To answer your first question, since arithmetic expressions are dependent on the data types and their representations, I do not think that there is a solely arithmetic expression that would be equivalent to the expression i & -i. In essence, the code below would be equivalent in functionality to that expression. (assuming that i is of type int) Notice, though, that I had to make use of a loop to produce the same functionality, and not just arithmetics.

int tmp = 0, k; while(tmp < 32) {     if(i & (1 << tmp))     {         k = i & (1 << tmp);         break;     }     tmp++; } i += k; 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: