Determine the sign of a 32 bit int

后端 未结 8 2085
天涯浪人
天涯浪人 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:20

    Assuming the implementation defines arithmetic right shift:

    (x>>31) | !!x
    

    Unlike Mystical's answer, there is no UB.

    And, if you want to also support systems where right shift is defined to be arithmetic shift:

    ~!(x>>31)+1 | !!x
    

    Edit: Sorry, I omitted a ! in the second version. It should be:

    ~!!(x>>31)+1 | !!x
    

    This version is still dependent on the implementation being twos complement and having either arithmetic or logical right-shift, i.e. if the implementation-defined behavior were something else entirely it could break. However, if you change the types to unsigned types, all of the implementation-defined behavior vanishes and the result is -1U, 0U, or 1U depending on the "sign" (high bit and zero/nonzero status) of x.

提交回复
热议问题