It is unclear what you want to achieve. Masking the low bits while keeping the sign bit is something you could do with a single mask on architectures where
int is represented as sign / magnitude. It is quite unlikely that you would be thinking of this peculiar case. What is your goal then ?
Be aware that masking is not the same as limiting the range. Except in the most trivial cases, limiting the range cannot be achieved with masking (the trivial cases being limiting to
0..0 and limiting to
If you just want to limit the range use this:
int j = i < -31 ? -31 : i > 31 ? 31 : i;
You can substitute any
int values for minimum and maximum.
i is evaluated twice in this expression: if you substitute a complex expression, it better to use a temporary variable. In some cases, the compiler can generate code without jumps for these tests, forget trying to do this by hand.
solved How to limit signed int with AND operator in C?