This was part of a larger programming assignment that was due for me last night. Couldn't figure out this problem, but I'm curious as to how it could be solved.
The function int greatestBitPos(int x)
should return an int mask that marks the position of the most significant bit. If x==0, return 0. No control structures (if, while, ?:) allowed.
Example: greatestBitPos(96) = 0x40
Legal operators: ! ~ & ^ | + << >> =
This website on bit twiddling is something I used as a starting point, especially the second algorithm. However, it uses <
comparisons, something this problem doesn't allow.
All ideas are welcome, thanks!
Edit: Please assume 2's complement, 32-bit integers. For all negative numbers, they have their topmost bit set, so the return value should be 0x80000000
.