Determine the sign of a 32 bit int

后端 未结 8 1533
隐瞒了意图╮
隐瞒了意图╮ 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);
    }
    

提交回复
热议问题