Checking whether a number is positive or negative using bitwise operators

后端 未结 16 794
轮回少年
轮回少年 2020-12-08 20:01

I can check whether a number is odd/even using bitwise operators. Can I check whether a number is positive/zero/negative without using any conditional statements/operators l

16条回答
  •  醉梦人生
    2020-12-08 20:29

    This can not be done in a portable way with bit operations in C. The representations for signed integer types that the standard allows can be much weirder than you might suspect. In particular the value with sign bit on and otherwise zero need not be a permissible value for the signed type nor the unsigned type, but a so-called trap representation for both types.

    All computations with bit operators that you can thus do might have a result that leads to undefined behavior.


    In any case as some of the other answers suggest, this is not really necessary and comparison with < or > should suffice in any practical context, is more efficient, easier to read... so just do it that way.

提交回复
热议问题