Determine the sign of a 32 bit int

后端 未结 8 1443
隐瞒了意图╮
隐瞒了意图╮ 2021-02-08 23:05

Using ONLY:

! ~ & ^ | + << >>

NO LOOPS

I need to determine the sign of a 32 bit integer and I need to return 1 if positive, 0 if 0 and -1 if ne

相关标签:
8条回答
  • 2021-02-08 23:32

    Why do you need to use bitwise operators for that?

    int get_sign(int value)
    {
        return (value < 0) ? -1 : (int)(value != 0);
    }
    

    If you absolutely have to use bitwise operators, then you can use the & operator to check for negative values, no shifting needed:

    int get_sign(int value)
    {
        return (value & 0x80000000) ? -1 : (int)(value != 0);
    }
    

    If you want to shift:

    int get_sign(int value)
    {
        return ((value >> 31) & 1) ? -1 : (int)(value != 0);
    }
    
    0 讨论(0)
  • 2021-02-08 23:35

    Dimitri's idea could be simplified to (!!x) - ((x >> 30) & 2)

    And just to give one more cryptic solution:

    ~!x & ((-((unsigned) x >> 31)) | !!x)
    
    0 讨论(0)
提交回复
热议问题