Change sign using bitwise operators

后端 未结 3 1268
半阙折子戏
半阙折子戏 2021-01-25 19:35

How to change the sign of int using bitwise operators? Obviously we can use x*=-1 or x/=-1. Is there any fastest way of doing this?

I did a sm

3条回答
  •  忘掉有多难
    2021-01-25 20:17

    Java uses Complement Two representation. In order to change a sign, it means you must do a bitwise negation (it would be equivalent to xor with FFFF) and add 1.

    x = ~x + 1;
    

    I am almost sure that -x is, if anything, faster than that.

提交回复
热议问题