سؤال

How would I go about setting up an if statement using only the following bitwise operations:

  • !
  • ~
  • &
  • ^
  • |
  • +
  • <<
  • >>

As an example: "if x is negative then add 15"

This would mean that if the input was x = 0xF0000000, then we would produce 0xF000000F. If the input was x = 0x00000004, we would produce 0x00000004.

هل كانت مفيدة؟

المحلول

You can add 15 to a number if it is negative, and 0 otherwise as follows. Shifting a negative number right will shift in 1's if the value is negative, and 0's otherwise. Shifting by 31 will fill the int with either 1's or 0's. ANDing by 0xF will set the summand to 15 if it is negative, and 0 otherwise, resulting in no change to x.

x += (x >> 31) & 0xF;

If you're worried about the implementation dependent behavior of shifting a signed number to the right. You can do the same thing with the following code, however you still are depending on a two's complement representation of the number. The shift results in 0 or 1, the multiplication scales the number to the appropriate value.

 x += (((unsigned)x >> 31) * 0xF);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top