Question: Can someone explain the logic behind this function. It works as intended /* * greatestBitPos - return a mask that marks the position of the

Can someone explain the logic behind this function. It works as intended

/*

* greatestBitPos - return a mask that marks the position of the

* most significant 1 bit. If x == 0, return 0

* Example: greatestBitPos(96) = 0x40

* Legal ops: ! ~ & ^ | + << >>

* Max ops: 70

* Rating: 4

*/

int greatestBitPos(int x) {

int p=!x+(~0);

int q=x>>31;

x=x|(x>>1);

x=x|(x>>2);

x=x|(x>>4);

x=x|(x>>8);

x=x|(x>>16);

x=(x>>1)+1;

return (x&p)+((1<<31)&q);

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!