Checking whether a number is positive or negative using bitwise operators

后端 未结 16 1037
轮回少年
轮回少年 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:13

    When you're sure about the size of an integer (assuming 16-bit int):

    bool is_negative = (unsigned) signed_int_value >> 15;
    

    When you are unsure of the size of integers:

    bool is_negative = (unsigned) signed_int_value >> (sizeof(int)*8)-1; //where 8 is bits
    

    The unsigned keyword is optional.

提交回复
热议问题