Determine the sign of a 32 bit int

后端 未结 8 2083
天涯浪人
天涯浪人 2021-02-08 22:38

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:37

    What about:

    int getsign(int n)
    {
      return (!!n) + (~((n >> 30) & 2) + 1);
    }
    

    ..for 32-bit signed int, 2's complement only.

    !!n gives 1 if n is nonzero. ((n >> 30) & 2) gives 2 iff the high bit (sign) is set. The bitwise NOT and +1 take the 2's complement of this, giving -2 or 0. Adding gives -1 (1 + -2) for negative values, 0 (0 + 0) for zero, and +1 (1 + 0) for positive values.

提交回复
热议问题