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);